tidwall / gjson

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

JSON only get keys in first level #297

Closed orhan-cmd closed 1 year ago

orhan-cmd commented 1 year ago

I need to print all first level keys from JSON, how can I do this?

Example:

json := `{
            "data": {
                "first": {
                    "second": [
                        1,
                        2,
                        3,
                        4
                    ]
                },
                "staleData": null
            }
        }`
printFirstLevelKeys(json) // this method should print all first level keys.

output $ data, first, second

volans- commented 1 year ago

@orhan-erday From your example it seems to me that you want to extract the "first" key for each nested object, but the JSON specification states that An object is an unordered set of name/value pairs (source), so there is no concept of "first" key in an object and it's implementation-dependent.

That said I guess you could leverage the @keys modifier in a recursive way.

In case you know in advance the number of nested layers your object has, then you could leverage the @values modifier and generate dynamically a multipath query: [@keys.0,@values.0.@keys.0,@values.0.@values.0.@keys.0] that would give you: ["data","first","second"]

orhan-cmd commented 1 year ago

Thank you so much!