0

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)?

metawops
  • 347
  • 2
  • 10

1 Answers1

1

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']
gregsdennis
  • 7,218
  • 3
  • 38
  • 71
  • Awesome! This works indeed, at least with the implementation that's used in the VSCode extension I mentioned above in my original post. This returns a single (flat) array that contains ids and labels in an alternating matter. I suppose it's not possible to create dictionaries (as array elements) that contain two key/value pairs for and id and a label, right? – metawops Aug 01 '23 at 08:59
  • 1
    No, that's not possible. JSON Path doesn't have any mechanism for restructuring the data. It's just a query and returns anything it finds. – gregsdennis Aug 01 '23 at 22:25
  • 1
    That said, there may be a way with the implementation to return the _paths_ to the values it finds. Using that, you can extrapolate which is the `id` and `label`. My implementation at https://json-everything.net/json-path will return both. – gregsdennis Aug 01 '23 at 22:26
  • Thanks so much, Greg! – metawops Aug 03 '23 at 07:16