How to Get All Objects with Jsonpaths in Golang

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

1 Answer

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

package main

import (
    "fmt"

    ""
    ""
)

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest