How to access deeply nested JSON data using Go (lang)?

Most often developer needs to consume JSON data from other service and query over them. Querying JSON document is little time-consuming.



Most often developer needs to consume JSON data from other service and query over them. Querying JSON document is little time-consuming. For the last few days, I was working on a package for Golang to query JSON data easily.

Let’s take a sample JSON data to start with:


Let’s find a deeply nested property and handle error properly, in this case, we’ll try to access name from the second element of items array, note: items is a property of vendor object. See the example below:


Example 1

Query: select * from vendor.items where price > 1200 or id null Using gojsonq we can do the query like:


Example 2

Query: select name, price from vendor.items where price > 1200 or id null.

Using gojsonq we can do the query like:


Example 3

Query: select sum(price) from vendor.items where price > 1200 or id null

Using gojsonq we can do the query like:

Example 4

Query: select price from vendor.items where price > 1200
Using gojsonq we can do the query like:

Example 5

Query: select * from vendor.items order by price
Using gojsonq we can do the query like:


Example 6

Using gojsonq You can handle errors properly, see the code snippet below:

Example 7

Let’s assume we have a JSON document like this one

We want to run a query like this:
Query: select * from users where name.first=John

Using the package you can do the query easily, see the code snippet below:

You can access nested level property using DOT (.) for methods like Where/GroupBy/SortBy etc . You can also use Alias and nested property selection using Select method.
Note: There are some other useful methods to make life easier! If you like the package do not forget to share with your community and star the repository

Thank you very much for reading this article and don’t forget to give your feedback on comment :)

Never miss a post from Chris Gregori, when you sign up for Ednsquare.