简体   繁体   中英

Extract data from nested JSON - Python

I have the following output from a HTTP Request and I'm trying to filter out the data to extract two bits of info.

{
"error": false, 
"statusCode": 200, 
"message": "OK", 
"data": {
    "lastChecked": "2020-03-16T22:02:35.106Z", 
    "sales_stats": [
        {"department": "online", 
        "country": "United Kingdom", 
        "orders": 11840, 
        "delivered": 2101}, 

        {"department": "instore", 
        "country": "United Kingdom", 
        "orders": 120, 
        "delivered": 95}, 

        {"department": "other", 
        "country": "United Kingdom", 
        "orders": 35, 
        "delivered": 1}
        ]}}

I only care about department online and I just need to display orders and delivered from that.

I have tried to extract this however to no avail.

All I want is the following bit of code.

data_orders = <11840 extracted from the response>
data_delivered = <2101 extracted from the response>

print("Orders = ", data_orders)
print('Delivered = ", data_delivered)

For the final outcome of

Orders = 11840
Delivered = 2101

Try something like this:

json = {
  "error": False,
  "statusCode": 200,
  "message": "OK",
  "data": {
    "lastChecked": "2020-03-16T22:02:35.106Z",
    "sales_stats": [
      {
        "department": "online",
        "country": "United Kingdom",
        "orders": 11840,
        "delivered": 2101
      },
      {
        "department": "instore",
        "country": "United Kingdom",
        "orders": 120,
        "delivered": 95
      },
      {
        "department": "other",
        "country": "United Kingdom",
        "orders": 35,
        "delivered": 1
      }
    ]
  }
}

json_data = json["data"]

# The online department is the first element in the sales_stats list
online_data_orders = json_data["sales_stats"][0]["orders"]
online_data_delivered = json_data["sales_stats"][0]["delivered"]

print(f"Orders = {online_data_orders}")
print(f"Delivered = {online_data_delivered}")

Output:

Orders = 11840
Delivered = 2101
resp = requests.get(url=url, params=params)
data = resp.json()
data_orders = data['data']['sales_stats'][0]['orders']

you can do similar for data_delivered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM