Search code examples
jsonpathjson-path-expression

Can I get more than just one key's value with JSONPath?


Here's a simplified (and syntactically not correct, because I stripped it) version of a JSON I'm currently dealing with:

{
  "data": {
    "134001": {
      "id": 134001,
      "label": "Deutsche Telekom",
      "is_active": true,
    },
    "134002": {
      "id": 134002,
      "label": "T-Mobile",
      "is_active": false,
    },
    "134004": {
      "id": 134004,
      "label": "1&1",
      "is_active": true,
    },
    "134005": {
      ...
    }
  }
}

Now when I use the JSONPath query string $.data..[?(@.is_active==true)].label I get all the labels of all the entries in data that have the key is_active set to true. That works fine (for example with the VSCode extension "JSON Path" bei Wei Junyu). I could also get the id instead of the label when I use the query $.data..[?(@.is_active==true)].id. Works fine, too.

But what I really want is to get both, the id and the corresponding label. The JSON contains much more details for each data entry and it's quite long. I want to extract a list of all the (id, label) pairs of all those dictionary items that have is_active set to true.

Is this a all possible with JSONPath alone? Or would I need other tools here? If so, which one(s)?


Solution

  • It'll depend on what the implementation supports, but a common syntax is a comma-delimited list inside square brackets.

    $.data..[?(@.is_active==true)]['id','label']