1

I have my JSON file:

[
   {
      "order_":{
         "id":"B2B78502",
         "status_order_id":5,
         "status_order_name":"Sent",
         "customer_id":256,
         "order_products":[
            {
               "order_product":{
                  "id":83630,
                  "order_id":79288,
                  "product_id":13519,
                  "quantity":"1.0",
                  "price":"72.44",
                  "addressbook_":{
                     "name":"user user",
                     "address":"adress",
                     "city":"THIENNES",
                     "country":"FR",
                     "postal_code":"59189",
                     "phone":"000000000"
                  },
                  "product_name":"product",
                  "product_code":"20159"
               }
            }
         ],
         "customer_email":"[email protected]",
         "customer_company":"SARL"
      }
   }
]

I want to insert data into a MySQL table, but I can not access all the values

here is my code:

json_obj = r.json()

for ord in json_obj:
    print("id:", ord["order"]["id"])
    print("order_produvt_id:", ord["order"]["order_products"]"order_product"]["id"])
    print('---')

I want to access all the data I want to access all the data but I get this error :

  id: B2B78588
    print("order_product_id:", ord["order"]["order_products"]["order_product"]["id"])
TypeError: list indices must be integers or slices, not str
3
  • That's not JSON. Commented Aug 3, 2018 at 13:43
  • and check this link. Commented Aug 3, 2018 at 13:46
  • it's a JSON recover from an API Commented Aug 3, 2018 at 13:48

1 Answer 1

1

In side "order_products", you have an array, indicated by these braces: [ ].

You need to access arrays with Integers, like the error tells you.

ord["order"]["order_products"][0]["order_product"]["id"]

The above example should work.

Sign up to request clarification or add additional context in comments.

2 Comments

yes you are right thank you, I did not pay attention that it is an array, I tried your code, I get this error: KeyError: 'id'
Edited my answer. I missed that "id" was in the "order_product" object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.