0

I am trying to parse a json but i am running into an error. Using this json as an example:

  "creator": "Deliveries",
  "sales": [
    {
      "sale_id": 123,
      "sale_date": "2021-01-01",
      "pickup_from": {
        "location_id": 321,
        "city": "Washington",
        "state": "VA"
      }
    }
  ]
}

and trying to print sale_id and sale_date and amount from sales and location_id and city from pickup_from using the code:

for sale in file_json['sales']:
        
    for store in sale['pickup_from']:
        print(sale['sale_id'])
        print(sale['sale_date'])
        print(store['location_id'])
        print(store['city'])

looking to the output:

123
2021-01-01
321
Washington

I am getting type error:

TypeError                                 Traceback (most recent call last)
<ipython-input-75-5dda8493c9d7> in <module>
     46         print(sale['sale_id'])
     47         print(sale['sale_date'])
---> 48         print(store['location_id'])
     49         print(store['city'])

TypeError: string indices must be integers

I know Im parsing it incorrectly, but not sure where Im going wrong.

  • 1
    did you at least `print(store)` to see the problem ? – azro Jun 19 '22 at 12:43
  • I did.. looks like I needed to add an additional key and there is no need to loop over twice: ```for sale in file_json['sales']: print(sale['sale_id']) print(sale['sale_date']) print(sale['pickup_from']['location_id']) print(sale['pickup_from']['city']) ``` – Mariusz Szymoniak Jun 19 '22 at 13:02

0 Answers0