Home > Back-end >  jmespath how do I find the key values in the dictionary?
jmespath how do I find the key values in the dictionary?

Time:03-04

I have an example json file. I need to extract all the values of the downloadUrl keys:

{
  "nodes": {
    "children": [
      {
        "id": "",
        "localizedName": "",
        "name": "Documents",
        "children": [
          {
            "id": "",
            "localizedName": "Brochures",
            "name": "Brochures",
            "items": [
              {
                "title": "Brochure",
                "downloadUrl": "/documents/brochure-en.pdf",
                "fileType": "pdf",
                "fileSize": "2.9 MB"
              }
            ]
          },
          {
            "id": "192194",
            "localizedName": "",
            "name": "Demonstrations",
            "items": [
              {
                "title": "Safety Poster",
                "downloadUrl": "safety-poster-en.pdf",
                "fileType": "pdf",
                "fileSize": "1.1 MB"
              }
            ]
          }
        ]
      }
    ]
  }
}

I'm trying to do this with this query:

jmespath.search('nodes[*].downloadUrl', file)

but the list of values is not displayed.
Where is the error?

CodePudding user response:

You need to do something like.

.search(("nodes[*].children[*].items[*].downloadUrl"))

CodePudding user response:

Statically, your property is under

nodes 
  children 
  [ ] 
    children 
    [ ] 
      items 
      [ ] 
        downloadUrl

So a query giving you those values would be:

nodes.children[].children[].items[].downloadUrl

If you want something a little more dynamic (let's say that the property names can change but the level at which you will find downloadUrl won't, you could use this query:

*.*[][].*[][].*[?downloadUrl][][].downloadUrl

But sadly, something like querying in an arbitrary structure, like you can do it in is not something JMESPath supports at the moment.

  • Related