1

I am still new to Python and at this moment I am experimenting with GET requests and only show values from one specific String.

import requests
import json

response = requests.get("APIURL")
data = response.text
parsed = json.loads(data)
id = parsed["products"][0]["id"]
print(id)

As you can see in the code above I don't have a for loop yet, already tried different things but still didn't get it working. With the code above I get the 'id' of only the first product, of the other products I don't get the results back.

The printed output, for the dict loaded from JSON, looks as follow:

{
    products: [
        {
            id: 66057248,
            createdAt: "2018-02-28T14:55:22+01:00",
            updatedAt: "2018-02-28T14:55:22+01:00",
            isVisible: true,
            visibility: "visible",
            hasMatrix: false
        }
    ]
}

3 Answers 3

2

The solution of diek is the one that worked for me, edited my post because of this. The better code is:

import requests
import json
response = requests.get("")
data =response.text
parsed=json.loads(data)

for product in parsed['products']:
    print(product['id'])

The output will look as follow:

66057248
66057245
66057242
66057239
66057236
66057233
66057230
66057227
66057224
Sign up to request clarification or add additional context in comments.

7 Comments

Giving one item in your example was not clear. If the structure is 'products': [ {'id': 66057248}, {'id': 66057245},....], there is absolutely no need to use range and len
If your json is formatted like this, dpaste.de/RUzV Then all you need is, dpaste.de/5gc2
First, Python makes iteration so much easier than other languages. You do not have to account for the length, Python manages this. If you want to get a good understanding of it, watch Ned Batchelder's PyCon video Loop Like a Native. 29 minutes well spent
Second, when I have data['products'], I have a list of dictionaries. No index is required. I then use the dictionary key, 'id', to access the value/data on each iteration. In more complex structures you may need to use an index to drill down
Thank you very much @diek for the information and for the video, much appreciated! I have edited my answer above as you can see :)
|
1

You can do:

for product in parsed:
    for index in parsed[product]:
        for element in parsed[product][index]:
            print(element.id)
            print(element.createdAt)
            # ...

In Simon's answer the id value in the loop would actually be 'id', 'createdAt' and etc. To print only ids as it suggests you need to assert if the key is equals to 'id', what makes the loop useless.

Note: It is not suggested to use id as variable name. It is a reserved word, in this case you can add the underscore getting id_ instead.

2 Comments

Which values do I have to change to merge this with my existing code and which values do I have to remove from my existing code?
If I got your question right, if you change your 2 last lines for this for, it will print every id and createdAt for every element for every product in parsed dictionary
0

Json uses a dictionary so you could use keys() to get all the possible values and then initerate through them:

for id in parsed["products"][0].keys():
    print(parsed["products"][0][id])

Figured it out:

This is not json. It is YAML (because your code lacks " (speech marks)). You need a YAML parser to run this. Once you have then it will run correctly.

5 Comments

Hi I tried your code, maybe I did something wrong But my output looks as follow: 66057248 66057248 66057248 66057248 66057248 66057248 As you can see it keeps looping the first product over and over again and doesn't get the ID of the other products.
@Solaiman What happens if you change the value of id as suggested below? Do you get the same result?
yes forgot to mention , I had already changed the value of the id as suggested below. So yeah same results.
Thanks for your help @Simon , I managed to solve it. And it is json :P, anyway this code below worked: import requests import json response = requests.get("") data =response.text parsed=json.loads(data) for i in range(0,len(parsed["products"])): print(parsed["products"][i]["id"])
You could write your own answer and accept that rather than accept my answer. You solution seems a lot different to mine. @Solaiman

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.