JSON and finding values in a list, int is not iterable

Question:

I imported a JSON query that I got from ‘https://fakerapi.it/api/v1’.

#Imports
import requests
import json

###############################
#         Start of code       #
###############################

#Variables for get request
BASE_URL = 'https://fakerapi.it/api/v1'
get_request = "products?_quantity=1"

#Get request
product= requests.get(f"{BASE_URL}/{get_request}")

#Load dictionary 
indentent_result= json.dumps(product.json(),indent=4)
dictionary = json.loads(indentent_result)

#Variables for categorie search
product1 = dictionary['data']
all_categories = product1[0]['categories']

#Finding out if there's a 3 in the product categories
for categories in all_categories:
    if 3 in categories:
        print("There's a 3 in the categories")

Here’s the JSON query:

{
    "status": "OK",
    "code": 200,
    "total": 1,
    "data": [
        {
            "id": 1,
            "name": "Et qui sit eum asperiores.",
            "description": "Est excepturi fuga cumque nulla. Aut molestiae perspiciatis dolore ducimus. Est provident at voluptatibus non. Odio perferendis quam totam provident iure sint est et.",       
            "ean": "0827583536838",
            "upc": "595145034526",
            "image": "http://placeimg.com/640/480/tech",
            "images": [
                {
                    "title": "Ullam aut iste eaque.",
                    "description": "Quaerat aspernatur earum dolores ea. Fugit quisquam aliquam et possimus reprehenderit est. Quis velit ipsa beatae quia.",
                    "url": "http://placeimg.com/640/480/any"
                },
                {
                    "title": "Odit aut eaque et aperiam.",
                    "description": "Quo facere quia voluptas autem. Aut sunt qui ut molestiae quaerat voluptatem. Officiis tenetur quasi non aut voluptatibus.",
                    "url": "http://placeimg.com/640/480/any"
                },
                {
                    "title": "Fugiat neque impedit qui ut.",
                    "description": "Soluta quidem ut ut eaque modi aut. Deleniti voluptates culpa est dolore libero omnis dignissimos. Distinctio fuga tempora nam sit corrupti cumque.",
                    "url": "http://placeimg.com/640/480/any"
                }
            ],
            "net_price": 8234438,
            "taxes": 22,
            "price": "10046014.36",
            "categories": [
                7,
                5,
                3,
                11
            ],
            "tags": [
                "rerum",
                "tempore",
                "vitae",
                "sequi"
            ]
        }
    ]
}

The problem is that, when I get to the loop, I get the error message

TypeError: argument of type 'int' is not iterable

I looked at the type of my variable and it’s a list with integers inside, so I don’t understand why I’m getting this error message. The only way I could get it to work was by using the following, but I would like to know why it’s not working the way I typed it initially.

for categories in all_categories:
    if categories == 3:
        print("There's a 3 in the categories")
Asked By: Jay Leblanc

||

Answers:

You did something like this:

all_categories = [7, 8, 9]
for categories in all_categories:
    if 3 in categories:
        print("There's a 3 in the categories")

So the first time through the loop it is attempting if 3 in 7:,
which won’t work, as an integer (7) is not iterable.
You could attempt if 3 in [7]:,
asking if it’s in a list, but that’s not what the OP code does.

The in operator iterates through a container or other iterable,
performing equality comparisons along the way.

The == operator typically looks at a pair of scalars to see if they’re the same.

Use the appropriate operator in the appropriate situation.


Rather than a plural identifier, prefer singular:

for category in all_categories:

It doesn’t make a difference to the machine.
But it will help you to better reason about the code.

Answered By: J_H

First the return value of the request() is a response object. You must access the contents of the request which is a JSON string then convert it to a dictionary object using the json() function.

import requests
import json

# Variables for get request
BASE_URL = 'https://fakerapi.it/api/v1'
get_request = "products?_quantity=1"

# Get request
response = requests.get(f"{BASE_URL}/{get_request}")
data = response.json()

# Variables for categories search
products = data['data']
categories = products[0]['categories']

The categories variable is a list so don’t need the for loop – just use the in operator on the list to test if the value 3 is within the list.

if 3 in categories:
    print("There's a 3 in the categories")
Answered By: CodeMonkey
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.