4

I have a JSON file recover from requests.get

here is some of my JSON:

 [{"order":{"id":"B4589B26","status_order_id":5,"status_order_name":"Sent","customer_id":326
"order_products":[{"order_product":{"id":96218,"order_id":96538,"product_id":59320,}}],"customer_email":"[email protected]","customer_company":"SARL","customer_name":"user user", .....

here is my code:

token = "xxxx"

r = requests.get('url', auth=('[email protected]', token))

mydb = pymysql.connect(host='localhost',
user='root',
passwd='user',
db='ytm_db')

cursor = mydb.cursor()

data = r.json()
json_obj = json.loads(r)

for ord in json_obj["order"]:
    print("id:", ord["id"])
    print("status_id:", ord["status_order_id"])
    print('---')
    cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["id"], ord["status_order_id"], ord["customer_id"]))

#close the connection to the database.
mydb.commit()
cursor.close()
print ("Done")

I have this error:

    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'Response'

2 Answers 2

5

You do not need this line json_obj = json.loads(r) . r.json() returns you a json response.

Ex:

json_obj = r.json()

for ord in json_obj["order"]:
    print("id:", ord["id"])
    print("status_id:", ord["status_order_id"])
    print('---')
    cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["id"], ord["status_order_id"], ord["customer_id"]))

#close the connection to the database.
mydb.commit()
cursor.close()
Sign up to request clarification or add additional context in comments.

3 Comments

I tried with this code but I have this error : ** for ord in json_obj["order"]: TypeError: list indices must be integers or slices, not str** @Rakesh you have an idea please?
Looks like json_obj is a list try iterating it first
I am a beginner in python I did not understand, can you explain how to do or what to look for, please!
2

This is the right solution :

json_obj = r.json()

for ord in json_obj:
    print("id:", ord["order"]["id"])
    print("status_id:", ord["order"]["status_order_id"])
    print('---')
    cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["order"]["id"], ord["order"]["status_order_id"], ord["order"]["customer_id"]))

#close the connection to the database.
mydb.commit()
cursor.close()

Comments

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.