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

Saddam H
GolangID
Published in
2 min readJul 10, 2018

The article was originally published in hashnode, here is a copy to reach more audience.

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.go

Yahooooo! Very simple right? It looks like working with ORM of JSON data. Let's see some more example to query over the sample data.

Example 1

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

Using gojsonq we can do the query like:

example1.go

Example 2

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

Using gojsonq we can do the query like:

example2.go

Example 3

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

Using gojsonq we can do the query like:

example3.go

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:

example5.go

Example 6

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

example6.go

Example 7

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

users.json

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:

example7.go

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 :)

--

--

Saddam H
GolangID

Software Engineer, Pathao Inc | Open Source Enthusiast | Love to write elegant code | Gopher by passion | https://thedevsaddam.github.io