I know how to play with JSON and interfaces in go without too many problems.
I would like to let users choose a JSON element from a JSON string and to store the element pattern in a string so that I can dynamically load it later. I have the following JSON:
{
"id": 1,
"name": "A green door",
"price": 12.50,
"tags": ["home", "green"]
}
Of course this is easy if I want the id
element of my JSON , as id
is the string I'm going to save.
Now let's say I want tags[1].
You can see this gets harder and harder as the JSON gets more complicated. For example I could want to save a pattern similar to tags[1].data[0].values.id
and so on...
Basically I need to get a well defined element from my JSON and need to save the pattern to a string.
Does GO have a solution to this kind of problem without me implementing my own string parser?
There are several packages that I can think of that have tools to solve problems like this. Here are some examples off the top of my head:
1) github.com/jmoiron/jsonq
jq := jsonq.NewQuery(yourData)
jq.Int("id")
jq.String("tags", "0")
2) github.com/araddon/gou
:
jh := gou.NewJsonHelper(yourData)
jh.Int("id")
jh.Strings("tags[0]")
3) https://github.com/elgs/gojq
The packages are very similar, but slightly different function structure.