gjson
gjson copied to clipboard
Querying a object like an array
Given the following object:
{
"friends": {
"dale": {
"nets": ["ig", "fb", "tw"]
},
"jane": {
"nets": ["fb", "qq"]
},
"murphy": {
"nets": ["xq", "tw"]
}
}
}
I would expect the query "friends.#.nets" to return [ig, fb, tw, fb, qq, xq, tw]
but instead it returns empty. I would also expect "friends.*.nets" to work, but it just returns the value from the first entry (dale) - i.e. [ig, fb, tw]
How can I get a array with all "nets" elements appearing in the input?
The reason why friends.#.nets
doesn't work is that friends
is an object and not an array.
You can achieve the result you want with the query:
friends.@values.#.nets|@flatten
that returns:
["ig", "fb", "tw","fb", "qq","xq", "tw"]
Explanation:
-
@values
returns an array with the values of the friends object, discarding the keys -
#.nets
extract the value of thenets
key from each item of the array, returning:
[["ig", "fb", "tw"],["fb", "qq"],["xq", "tw"]]
-
|.@flatten
flattens the arrays into a single array. The pipe delimiter is needed in this case to apply the flatten after the previous operation. See the Dot vs Pipe section of the syntax page.
Ah, I guess I assumed that # was an alias for @values
on a object.