tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.21k stars 847 forks source link

Question - How do I parse array? #269

Closed vikas027 closed 2 years ago

vikas027 commented 2 years ago

I am more of a Python guy but trying my hands on GoLang :). My apologies, if the question is too simple.

I am trying to write a CLI where I get a Byte response and then I can do userID := gjson.GetBytes(body, "id") to get id from the the JSON string like "id":"111111","name":"xxxxx"}.

This works perfectly fine but I am trying to find a way to find the same ID, when I have a JSON string link [{"id":"111111","name":"xxxxx"}]. I am not sure how I can get the value of id using this package. I do have a workaround by using an interface like this but I am sure there is an easy way using gjson module :)

volans- commented 2 years ago

There are various options, most of them described in the SYNTAX.md, see the Array and Queries sections in particular. There is also a playground to test things online at gjson.dev.

In the case of arrays it depends what you want to get. There are various options. Given the following JSON for example:

[
    {"id":"1", "name":"Alice"},
    {"id":"2", "name":"Alice"},
    {"id":"3", "name":"Bob"}
]

Here some basic queries to get the IDs:

vikas027 commented 2 years ago

Awesome! Thanks, @volans for the examples, that really helped. I did have a look at this page but I guess the specific section.