jmespath how do I find the key values in the dictionary?
Asked Answered
T

2

1

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?

Torp answered 4/3, 2022 at 0:22 Comment(3)
You're searching in shallow hierarchy, while downloadUrl is deeply nested keys.Brann
if I know the hierarchy, why do I need the jmespath module?Torp
There is nothing in JMESPath like an XPath "search in any level" if that's what you are after, indeed.Planck
E
2

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.

Engrossment answered 4/3, 2022 at 12:58 Comment(0)
B
0

You need to do something like.

.search(("nodes[*].children[*].items[*].downloadUrl"))
Brann answered 4/3, 2022 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.