Jeffail/gabs

How can I create a complex JSON

Closed this issue · 3 comments

How can I create a complex JSON, like this:
{"body":
{"content":
[ {"a":"1","b":"2"},
{"c":"3","d","4"}
]
}
}

I try,but has no idea

It looks like its easy to parse or append to existing json since what ever you are creating is usually structured. gabs is more for unstructured json.

gabs project is for parsing, creating and editing unknown or dynamic JSON.

See this example from the README

jsonObj := gabs.New()

jsonObj.Set(10, "outter", "inner", "value")
jsonObj.SetP(20, "outter.inner.value2")
jsonObj.Set(30, "outter", "inner2", "value3")
fmt.Println(jsonObj.String())

Will print:

{"outter":{"inner":{"value":10,"value2":20},"inner2":{"value3":30}}}

No gabs is really powerful and you can do easily your JSON.

Here is how you can do this:

yourJson := gabs.New()

contentJson := gabs.New()
contentJson.Array("content")

firstArrayContent := gabs.New()
firstArrayContent.Set("1", "a")
firstArrayContent.Set("2", "b")

secondArrayContent := gabs.New()
secondArrayContent.Set("3", "c")
secondArrayContent.Set("4", "d")

//the magic begin here
contentJson.ArrayAppend(firstArrayContent.Data(), "content")
contentJson.ArrayAppend(secondArrayContent.Data(), "content")

yourJson.Set(contentJson.Data(), "body")

fmt.Println(yourJson.String())

Thanks @Majonsi