简体   繁体   中英

Importing data from JSON issue - Python

I am trying to parse data from JSON and print a values from a specific key(Crust). The issue is that I am getting an error TypeError: list indices must be integers, not str . This error is for the line Crust=response.json()['Crust'] Any ideas?

import requests
import json

if __name__=='__main__':

response=requests.get("https://order-pizza-api.herokuapp.com/api/orders")
Crust=response.json()['Crust']
jprint(Crust)

The response from https://order-pizza-api.herokuapp.com/api/orders is a list of objects, so you cannot index it like you would a dictionary. See below

[
  {
    "Crust": "NORMAL",
    "Flavor": "BEEF-NORMAL",
    "Order_ID": 1,
    "Size": "M",
    "Table_No": 1,
    "Timestamp": "2019-12-03T18:21:08.669365"
  },
  {
    "Crust": "THIN",
    "Flavor": "CHEESE",
    "Order_ID": 2,
    "Size": "S",
    "Table_No": 5,
    "Timestamp": "2019-12-03T18:21:08.708470"
  },
  {
    "Crust": "NORMAL",
    "Flavor": "CHICKEN-FAJITA",
    "Order_ID": 3,
    "Size": "L",
    "Table_No": 3,
    "Timestamp": "2019-12-03T18:21:08.710006"
  }
]

To get the crust, you will have to select a dictionary from the list and get the crust.

response = requests.get("https://order-pizza-api.herokuapp.com/api/orders")
resp_json = response.json()
print(len(resp_json))  # 3
print(resp_json[0]["Crust"])  # NORMAL
print(resp_json[1]["Crust"])  # THIN
print(resp_json[2]["Crust"])  # NORMAL

To get all of the crusts, one can iterate over the response and grab each crust.

[item["Crust"] for item in resp_json]

Try this:

In [19]: import ast

In [20]: response = requests.get("https://order-pizza-api.herokuapp.com/api/orders")

In [21]: ast.literal_eval(response.content.decode())
Out[21]:
[{'Crust': 'NORMAL',
  'Flavor': 'BEEF-NORMAL',
  'Order_ID': 1,
  'Size': 'M',
  'Table_No': 1,
  'Timestamp': '2019-12-03T18:21:08.669365'},
 {'Crust': 'THIN',
  'Flavor': 'CHEESE',
  'Order_ID': 2,
  'Size': 'S',
  'Table_No': 5,
  'Timestamp': '2019-12-03T18:21:08.708470'},
 {'Crust': 'NORMAL',
  'Flavor': 'CHICKEN-FAJITA',
  'Order_ID': 3,
  'Size': 'L',
  'Table_No': 3,
  'Timestamp': '2019-12-03T18:21:08.710006'}]

In [22]: [x['Crust'] for x in ast.literal_eval(response.content.decode())]
Out[22]: ['NORMAL', 'THIN', 'NORMAL']

Here is the oneliner:

In [33]: [x['Crust'] for x in requests.get("https://order-pizza-api.herokuapp.com/api/orders").json()]
Out[33]: ['NORMAL', 'THIN', 'NORMAL']

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