I need to get a value from json file by index (not by key)
Here is my json file
{
"db": {
"vendor": {
"product": {
"fruits": {
"price": {
"dollars": [
10,
2
],
"euros": [
11,
1.9
],
"pesos": [
16,
15
]
}
},
"vegatables": {
"price": {
"dollars": {
"0": 8,
"1": 2
},
"euros": {
"0": 10,
"1": 1.5
},
"pesos": {
"0": 15,
"1": 12
}
}
}
}
}
}
}
My goal - get values in dollars, euros and pesos for all "products" (in this json file it is fruits and vegatables only)
My code:
import json
path_to_file = "C:\\Users\\admin\\Documents\\kolos\\data\\vegs.json";
with open(path_to_file) as data_file:
data = json.load(data_file)
lenght_of_products = (len(data["db"]["vendor"]["product"]))
for x in range(lenght_of_back):
print(data["db"]["vendor"]["product"][x]["price"]["dollars"])
And I got
Traceback (most recent call last):
File "C:\\Users\\admin\\Documents\\kolos\\data\\vegs.json", line 12, in <module>
print(data["db"]["vendor"]["product"][x]["price"]["dollars"])
KeyError: 0
The problem is in X variable. If I try without it, for example code below, it works.
print(data["db"]["vendor"]["product"]["fruits"]["price"]["dollars"][0])
P.S
In my another program I use the similar code and it works great
...
for x in range(lenght_of_leagues):
print(data["leagues"][x]["id"])
...