How do I access deep nested JSON data with go?

Source: Internet
Author: User
Tags macbook

Original from Https://hashnode.com/post/how ...

In most cases, developers need to use and query JSON data from other services. Querying JSON documents is time consuming. In the past few days, I was writing a package for Golang to easily query JSON data. This idea and inspiration comes from Nahid Bin Azhar's Php-jsonq.

Let's look at a sample JSON data:

{   "name":"computers",   "description":"List of computer products",   "vendor":{      "name":"Star Trek",      "email":"info@example.com",      "website":"www.example.com",      "items":[         {"id":1, "name":"MacBook Pro 13 inch retina","price":1350},         {"id":2, "name":"MacBook Pro 15 inch retina", "price":1700},         {"id":3, "name":"Sony VAIO", "price":1200},         {"id":4, "name":"Fujitsu", "price":850},         {"id":5, "name":"HP core i5", "price":850, "key": 2300},         {"id":6, "name":"HP core i7", "price":950},         {"id":null, "name":"HP core i3 SSD", "price":850}      ],      "prices":[         2400,         2100,         1200,         400.87,         89.90,         150.10     ]   }}

Let's find a deep nested property and handle the error correctly, in which case we will try <font color= "Red" >name</font> from <font color= "Red" >items</ The second element of the font> array is accessed, note: <font color=red>items</font> is <font color= "Red" >vendor</font> The properties of the object.
See the following example:

package mainimport (    "fmt"    "log"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.Find("vendor.items.[1].name")    if jq.Error() != nil {        log.Fatal(jq.Errors())    }    fmt.Println(res)}

Yahooooo! Very simple, huh? It looks like using Ormjson data. Let's look at some more examples to query the sample data.

Example 1

Enquiry: <font Color=red>select * from Vendor.items where price > or ID null</font>

Using Gojsonq we can execute the following query:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.From("vendor.items").Where("price", ">", 1200).OrWhere("id", "=", nil).Get()    fmt.Println(res)    // output: [map[price:1350 id:1 name:MacBook Pro 13 inch retina] map[id:2 name:MacBook Pro 15 inch retina price:1700] map[id:<nil> name:HP core i3 SSD price:850]]}

Example 2

Query: <font color=red> select name, price from Vendor.items where price > or ID null</font>

Using Gojsonq we can execute the following query:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.From("vendor.items").Where("price", ">", 1200).OrWhere("id", "=", nil).Only("name", "price")    fmt.Println(res)    // output: [map[name:MacBook Pro 13 inch retina price:1350] map[name:MacBook Pro 15 inch retina price:1700] map[name:HP core i3 SSD price:850]]}

Example 3

Query: <font color=red> Select SUM (Price) from Vendor.items where price > or ID null</font>

Using Gojsonq we can execute the following query:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.From("vendor.items").Where("price", ">", 1200).OrWhere("id", "=", nil).Sum("price")    fmt.Println(res)    // output: 3900}

Example 4

Enquiry: <font color=red>select price from Vendor.items where price > 1200</font>

Using Gojsonq we can execute the following query:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.From("vendor.items").Where("price", ">", 1200).Pluck("price")    fmt.Println(res)    // output: [1350 1700]}

Example 5

Enquiry: <font color=red> SELECT * from Vendor.items ORDER by price</font>

Using Gojsonq we can execute the following query:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./sample-data.json")    res := jq.From("vendor.items").SortBy("price").Get()    fmt.Println(res)    // output: [map[id:<nil> name:HP core i3 SSD price:850] map[id:4 name:Fujitsu price:850] map[id:5 name:HP core i5 price:850 key:2300] map[id:6 name:HP core i7 price:950] map[id:3 name:Sony VAIO price:1200] map[id:1 name:MacBook Pro 13 inch retina price:1350] map[id:2 name:MacBook Pro 15 inch retina price:1700]]}

Example 6

With Gojsonq you can handle errors correctly, see the following code snippet:

package mainimport (    "log"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./invalid-file.xjsn")    err := jq.Error()    if err != nil {        log.Fatal(err)        // 2018/06/25 00:48:58 gojsonq: open ./invalid-file.xjsn: no such file or directory        // exit status 1    }}

Example 7

Let's say we have a JSON document like this

{  "users":[    {      "id":1,      "name":{        "first":"John",        "last":"Ramboo"      }    },    {      "id":2,      "name":{        "first":"Ethan",        "last":"Hunt"      }    },    {      "id":3,      "name":{        "first":"John",        "last":"Doe"      }    }  ]}

We want to run a query like this:

Query: <font color=red> SELECT * from Users where name.first=john</font>

This package makes it easy to query, see the following code snippet:

package mainimport (    "fmt"    "github.com/thedevsaddam/gojsonq")func main() {    jq := gojsonq.New().File("./data.json")    res := jq.From("users").WhereEqual("name.first", "John").Get()    fmt.Println(res) //output: [map[id:1 name:map[first:John last:Ramboo]] map[id:3 name:map[first:John last:Doe]]]}

You can use dot (. ) to access nested level properties, such as <font Color=red>where/groupby/sortby etc</font>

Note: There are other useful ways to make life easier! If you like the package, don't forget to share it with your community and star the repository

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.