gjson icon indicating copy to clipboard operation
gjson copied to clipboard

Querying a object like an array

Open paralin opened this issue 2 years ago • 2 comments

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?

paralin avatar Jul 05 '21 23:07 paralin

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 the nets 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.

volans- avatar Mar 30 '22 10:03 volans-

Ah, I guess I assumed that # was an alias for @values on a object.

paralin avatar Mar 30 '22 10:03 paralin