Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all objects with jsonpaths in golang

Tags:

json

go

jsonpath

I am using jsonpath in golang but I can't get all the objects of the following json that contain in type iPhone:

{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
    "streetAddress": "naist street",
    "city": "Nara",
    "postalCode": "630-0192"
},
"phoneNumbers": [
    {
        "type": "iPhone",
        "number": "0123-4567-8888"
    },
    {
        "type": "home",
        "number": "0123-4567-8910"
    },
    {
        "type": "iPhone",
        "number": "0123-4567-8910"
    }
]}

I am working with golang and I know that the following jsonpath works:

$.phoneNumbers[?(@.type == "iPhone")]

The problem I have is that it is a service in which I have input a json path like the following:

$.[*].phoneNumbers[*].type

And the value that I have to look for, I am doing it in the following way:

values, err := jsonpath.Get(jsonPath, data)
for _, value := range values {
    if err != nil {
        continue
    }
    if value.(string) == "iPhone" {
                
    }
}

At this point I cant get the output like:

[{
    "type": "iPhone",
    "number": "0123-4567-8888"
},
{
    "type": "iPhone",
    "number": "0123-4567-8888"
}]

I cant use the [?(@.)] format it is necessary to make with if. Any idea? Thanks

like image 978
Fernando González Avatar asked Oct 15 '25 14:10

Fernando González


1 Answers

I cooked up an example using Peter Ohler's ojg package. Here's what the implementation looks like:

package main

import (
    "fmt"

    "github.com/ohler55/ojg/jp"
    "github.com/ohler55/ojg/oj"
)

var jsonString string = `{
// Your JSON string
}`

func main() {
    obj, err := oj.ParseString(jsonString)
    if err != nil {
        panic(err)
    }

    x, err := jp.ParseString(`$.phoneNumbers[?(@.type == "iPhone")]`)
    if err != nil {
        panic(err)
    }

    ys := x.Get(obj)
    for k, v := range ys {
        fmt.Println(k, "=>", v)
    }
}
// Output:
// 0 => map[number:0123-4567-8888 type:iPhone]
// 1 => map[number:0123-4567-8910 type:iPhone]

Go Playground

like image 67
benSooraj Avatar answered Oct 17 '25 02:10

benSooraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!