jmespath / jmespath.py

JMESPath is a query language for JSON.
http://jmespath.org
MIT License
2.19k stars 181 forks source link

Usage Questions #296

Closed AkikoOrenji closed 1 year ago

AkikoOrenji commented 2 years ago

Sorry for perhaps a basic question but have structure as follows :

jsonData = """{ "products" : { "1" : { "sku" : "a", "attributes" : { "location" : "there", "time": ""500". "planet" : "earth" } }, "2" : { "sku" : "b", "something" : "1", "attributes" : { "location" : "here", "time": ""500". "planet" : "Mars" } }, "3" : { "sku" : "c", "something" : "3", "attributes" : { "location" : "there", "time": ""300". "planet" : "earth" } } } }"""

I'm trying to return all time values where planet = "earth". I've tried a few things and reviewed the excellent examples in your documentation but i'm still stuck. Any pointers would be really appreciated.

Minitour commented 2 years ago

Assuming you are using Python it should be something like this:

import jmespath

my_data = {
  "products": {
    "1": {
      "sku": "a",
      "attributes": {
        "location": "there",
        "time": 500,
        "planet": "earth"
      }
    },
    "2": {
      "sku": "b",
      "something": "1",
      "attributes": {
        "location": "here",
        "time": 500,
        "planet": "Mars"
      }
    },
    "3": {
      "sku": "c",
      "something": "3",
      "attributes": {
        "location": "there",
        "time": 300,
        "planet": "earth"
      }
    }
  }
}
jmespath.search("@.products.* | [? attributes.planet == 'earth'] | [].attributes.time", my_data)

This will result in :

[
  500,
  300
]
jamesls commented 1 year ago

Thanks for the answer!