DEV Community

Rick Cogley
Rick Cogley

Posted on

Query with jsonpath

If you work with REST interfaces for any amount of time, you'll run into "json path". You can extract and manipulate the json received with an API call.

If you take a look at the above-linked repo, or perhaps an online evaluator, you'll see some examples that are easy to grok, but one thing that's a little hidden is the way you can query for one thing, but return another.

For instance, if you have json which lists folders and files in a given folder, something like:

{
  "total_count": 3,
  "entries": [
    {
      "type": "folder",
      "id": "15136111",
      "sequence_id": "0",
      "etag": "0",
      "name": "202110"
    },
    {
      "type": "folder",
      "id": "15136222",
      "sequence_id": "0",
      "etag": "0",
      "name": "202111"
    },
    {
      "type": "file",
      "id": "8913111",
      "file_version": {
        "type": "file_version",
        "id": "958222",
        "sha1": "45cd8db245a5bd3ab79b6f5150a928ff7d0d18bc"
      },
      "sequence_id": "0",
      "etag": "0",
      "sha1": "45cd8db245a5bd3ab79b6f5150a928ff7d0d18bc",
      "name": "combofile3.pdf"
    }
  ],
  "offset": 0,
  "limit": 100,
  "order": [
    {
      "by": "type",
      "direction": "ASC"
    },
    {
      "by": "name",
      "direction": "ASC"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Say you want the id of the folder that is named "202111", which you know because all your folders are named consistently like that. Use this json path to get it:

.entries[?(@.name=="202111")].id
Enter fullscreen mode Exit fullscreen mode

(you might need .0.entries... or 0.entries depending on the circumstances)

In "entries", that looks for an entry with a name of "202111", and returns its id. Then you can use that id to, say, post new items to that folder. Sweet.

Top comments (0)