0

I am trying to assignment variables to the following json from a rest API:

.json

https://shopify.dev/docs/admin-api/rest/reference/products/product

.py


response = requests.get("https://{0}{1}".format(session.get("shop"), endpoint), headers=headers)
    print(response)

    #If connection has been successfull ...
    if response.status_code == 200:
        products = json.loads(response.text)

    for product in products:
        ###PRINT VARIABLES####
        print(product['id']
        print(product['title'])
        print(product['title']['variants']['product_id'])

The above however returns the following error.

KeyError: 'title'

I have further tried;

        print(products['product']['title']
        print(product(product).title

and various others with no success.

Any help parsing this json would be appreciated.

Thanks!

4
  • the JSON source file has a syntax error: add ", after 8GB Commented Apr 28, 2020 at 13:52
  • Can you update the question to show the complete error traceback of the error "KeyError: 'title'". Also, can you specify whats contained in response.text before doing json.loads Commented Apr 28, 2020 at 13:53
  • JSON is malformed, it cannot start from double quote " Commented Apr 28, 2020 at 13:56
  • this is the json reponse. shopify.dev/docs/admin-api/rest/reference/products/product Commented Apr 28, 2020 at 14:00

2 Answers 2

1

Your issue is not with loading the json data into products variable. After loading, you are trying to retrieve values from products in an incorrect manner which leads to Key Error. Your products is basically a dictionary of list of dictionary

Here is the correct way to retrieve necessary values from products:

print(products['products'][0]['id'])
#632910392
print(products['products'][0]['title'])
#IPod Nano - 8GB
print(products['products'][0]['variants'][0]['product_id'])
#632910392

Try analysing the deep structure of your products variable so that you can learn to retrieve any value in it by yourself. Cheers!

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

Comments

0

Consider accessing the array by using products["products"] for instance:

import json
result = json.loads('{"products": [ {"id": "1234", "title": "foo"} ]}')
for it in result["products"]:
    print("id: " + it["id"] + " title: " + it["title"])

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.