#335 Future JSON Implementation

mxp Fri 15 Aug 2008

Are you looking at implementing JSON into the code-base (I apologize if I have over looked it ) ?

Just for the sake of an hack example json generator in Fan (I had wanted to find some kind of example snippet like this in the forum..)

class JSON {

private Map m := [:]

private Str j(Map a)
{
  r := "{"
  a.each |Obj v, Obj k|
  {
    	s := v->type->name=="Map" ? "" : ", "

      v = fv(v)

      r += "\"$k\": $v$s"
  }
  return r+"}, "
}

private Str fv(Obj v)
{
  switch(v->type->name)
  {
    case "Map": v=j(v)
    case "List":
    	z:="["
      ((Int)v->size).times |Int x|
      {
        s := v->get(x)->type->name=="Map" ? "" : ", "
        z += fv(v->get(x))+s
      }
      z+="]"
      v=z.replace(", ]","]")
    case "Int": v=v.toStr
    default: v="\""+v+"\""
  }

  return v     
}

private Map p(Str a)
{
  return InStream.makeForStr(a.replace("{","[").replace("}","]")).readObj
}

new make(Obj a := [:])
{
  if(a->type->name=="Str") a=p(a)
  this.m = a
}

Obj get(Obj a){ return m[a] }

Obj set(Obj a, Obj b){ m[a]=b; return null}  

Str out(){ return j(m).replace(", }","}")[0..-3] }

}

class jsontest: Test {

Void main()
{
	j := JSON()
	j["method"]="samples.hello"
      echo(j.out)

      //or

	echo(JSON(["message":["date":"8.15.08","list":[9,8,"x"]]]).out)
}

}

brian Fri 15 Aug 2008

There is definitely going to be a standard json pod API for serializing to/from JSON. See the roadmap.

My current thinking is that default serialization models for both XML and JSON will work just like normal serialization using the @serializable and @simple tree model. Round trip serialization is a little tricky since we won't have types to map back to. So I would probably let you use optional type annotations or just map back to generic Obj:Obj maps.

In terms of priority, I would say the json API sits as follows:

  1. basic flux editor
  2. finish fwt to a good stopping point
  3. finish web apis
  4. XML apis
  5. JSON apis

Any remaining language features interspersed.

Login or Signup to reply.