tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.1k stars 845 forks source link

Querying a object like an array #224

Open paralin opened 3 years ago

paralin commented 3 years ago

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?

volans- commented 2 years ago

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:

paralin commented 2 years ago

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