tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.2k stars 846 forks source link

How to get values from .Array() from nested object all in one go #347

Closed fracasula closed 7 months ago

fracasula commented 7 months ago

Given this small example:

func TestParsing(t *testing.T) {
    data := `[{
        "workspaces": {
            "wc-1": {
                "updatedAt": "2009-11-17T20:34:58.651387237Z"
            },
            "wc-2": {
                "updatedAt": "2009-11-21T20:34:58.651387237Z"
            },
            "wc-3": {
                "updatedAt": "2009-11-19T20:34:58.651387237Z"
            }
        }
    }]`
    result := gjson.Get(data, "#.workspaces.@values.#.updatedAt")
    if len(result.String()) > 0 {
        result = gjson.Get(result.String(), "0.@values")
    }
    for _, v := range result.Array() {
        t.Log(v.String())
    }
}

I get the correct output:

=== RUN   TestParsing
    parsing_test.go:195: 2009-11-17T20:34:58.651387237Z
    parsing_test.go:195: 2009-11-21T20:34:58.651387237Z
    parsing_test.go:195: 2009-11-19T20:34:58.651387237Z
--- PASS: TestParsing (0.00s)

I find it hard to figure out how to do it in one go though.

These do not seem to work:

Can you help please?

volans- commented 7 months ago

@fracasula if you have one of the latest releases of GJSON you can use the new @dig modifier (see SYNTAX.md):

@dig:updatedAt

or, using the standard approach you can use (see the Dot vs Pipe section of the syntax docs):

#.workspaces.@values.#.updatedAt|0

In both cases they return:

["2009-11-17T20:34:58.651387237Z","2009-11-21T20:34:58.651387237Z","2009-11-19T20:34:58.651387237Z"]
fracasula commented 7 months ago

Right, that makes sense, thanks @volans-! :+1: