tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
13.88k stars 841 forks source link

Querying nested optional array #331

Closed mgdemers closed 9 months ago

mgdemers commented 9 months ago

I am looking to retrieve values from a nested array that may not always be present, and preserve the array ordering in the result.

Example JSON:

{
    "outer": {
         "middle": [
             {
                 "otherKey": "otherVal"
             },
              {
                 "otherKey": "otherVal",
                 "inner": [{"key": "value"}, {"key": "value2"}]
             },
             {
                 "inner": [{"key": "value3"}]
             },
        {
            "inner": null
        }
         ]
    }
}

Ideally, I want to get something like this output:

[nil, ["value","value2"],["value3"], nil]

Based on comments in #295, I've tried a few variations of queries with defaults defined, but the null or omitted keys are still dropped from the results:

outer.[middle, !null].0.#.[inner, !null].0.#.[key, !null].0 -> [["value","value2"],["value3"]]

The closest I've come is here, where the general structure is still defined, but technically wrapped in one extra layer of brackets:

outer.[middle, !null].0.#.[inner, !null].[0.#.key, !null]  ->  [[],[["value","value2"]],[["value3"]],[]]

Any ideas for how I can preserve the empty & missing arrays is greatly appreciated!

volans- commented 9 months ago

@mgdemers I think that the problem in your query are the spaces and in your last example you're missing a .0 at the end, with:

outer.[middle,!null].0.#.[inner,!null].[0.#.key,!null].0

I get

[null,["value","value2"],["value3"],null]

That I believe is what you're looking for.

mgdemers commented 9 months ago

Thanks @volans- , removing the spaces was what I needed.