Home > database >  Python, Trying to get hold of a value from a nested JSON file (beginner)
Python, Trying to get hold of a value from a nested JSON file (beginner)

Time:04-05

This is a sample of my json file, it looks the same for all other products. How to get hold of the value "delivery". in some products the "delivery" key is in 2nd position after "pickup" so i don't wanna use index slicing.


{
    "products": {
        "O5PPQ": {
            "name": "Hyundai",
            "imageUrl": null,
            "variants": [
                {
                    "id": "O5PPQ",
                    "name": null,
                    "shippingTypes": [
                        "DELIVERY"
                    ],
                    "prices": {
                        "delivery": 1200,
                        "pickup": 1200,
                        "deposit": null
                    }
                }
            ]
        }
    }
}

This is as far as i could get with my code

import json
with open (r"filepath\test.json") as file:     
data = json.load(file)     
products = data["products"]     
product = products["O5PPQ"]     
print(product["variants"])

when i try this:


print(product["variants"]["prices"]["delivery"])

i get this:

TypeError: list indices must be integers or slices, not str

CodePudding user response:

You are trying to access a list of "variants", indicated by the starting bracket "[" of the field, hence the error.

If you want to access the "delivery" field of "prices" you need to select the "price" field from the list of "variants" which has the index zero.

I accessed the desired field via this statement:

print(product["variants"][0]["prices"]["delivery"])

With output: 1200

The following source from the W3 schools explains lists in JSON quite nicely.

  • Related