In go
the standard package encoding/json exposes json.Unmarshal
function to parse JSON.
It's possible to either unmarshal the JSON string in a predefined struct
, or use the interface{}
and iterate the result for unexpected JSON data structure.
That said, I can't parse complex JSON properly. Can someone tell me how to achieve this?
{
"k1" : "v1",
"k2" : "v2",
"k3" : 10,
"result" : [
[
["v4", v5, {"k11" : "v11", "k22" : "v22"}]
, ... ,
["v4", v5, {"k33" : "v33", "k44" : "v44"}
]
],
"v3"
]
}
Citing from JSON and Go:
More information about Go and JSON can be found in the original article. I changed the code snippets slightly to be more similar to the JSON in the question.
Using standard library
encoding/json
packageI've worked of JSON and Go article, and it turned out that
case int
doesn't work and it need to becase float64
now, and there is plenty of nesting in real-world JSON.I've also looked at JSON decoding in Go, but it didn't help me very much as I needed to do proceduralrly traform it into a series of calls to mruby binding, and the author of that article is happy with Go structs for most part.
I've spent a little while fiddling with this and final iterating dumper function looked like this:
With
b
being a byte slice with a JSON representing either an array or an object at the top-level, you can call it like this:Hope this helps, you try the comple program here.
Using other packages
I would recommend not doing it yourself, unless you feel you have to learn how Go types work and using
reflect
makes you feel like a master of the universe (personally,reflect
drives me mad).As @changingrainbows pointed out below, there is
github.com/tidwall/gjson
package, which appears to wrapencoding/json
and usesreflect
. I may be not dissimilar fromgithub.com/mitchellh/reflectwalk
, which is pretty hard to use and inner workings are rather very complicated.I have used
github.com/buger/jsonparser
rather extensively in one of my projects, and there is alsogithub.com/json-iterator/go
, which I've not tried yet, but it appears to be based ongithub.com/buger/jsonparser
and appears to exposeenconding/json
-compatible interface and hasfunc Get(data []byte, path ...interface{}) Any
as well. For the record, Kubernetes project has recently switched togithub.com/json-iterator/go
. In my project, I useencoding/json
as well asgithub.com/buger/jsonparser
, I'll probably switch togithub.com/json-iterator/go
when I have time. I will try to update this post with more findings.More recently, gjson offers selection of properties in JSON