tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.39k stars 857 forks source link

Query for node that doesn't have specified field #325

Closed taras-janea closed 1 year ago

taras-janea commented 1 year ago

Hi guys,

First, thank you for the awesome library!

I'm using the query functionality heavily and now I need to query an array element that doesn't have a specified field: For example, for next json:

  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]

I need to return the second item, cause it doesn't have an age: {"first": "Roger", "last": "Craig", "nets": ["fb", "tw"]}

I need a query like gjson.Get(friends, "friends.#(age is absent)"), but I don't know how to write it so it works.

Could you please help me?

tidwall commented 1 year ago

Try friends.#(age==~false)#.

It looks like a weird syntax but the '~' character converts a value to a boolean before comparison. In this case a non-existent value is converted to "false".

For more information: https://github.com/tidwall/gjson/blob/master/SYNTAX.md#queries