Alex Lian
Alex Lian

Reputation: 47

Python 3 get value by index from json

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"])
    ...

Upvotes: 1

Views: 17002

Answers (2)

ClydeTheGhost
ClydeTheGhost

Reputation: 1523

Here's a version that should work (depending on what you expect it to do):

  • I changed the dict() to an OrderedDict() to preserve the original ordering

  • I added .values() to the dictionary which is being indexed into. This method returns a list of all dictionaries which can then be indexed into

Here's the code:

import json
from collections import OrderedDict

path_to_file = "test.json";

with open(path_to_file) as data_file:
    data = OrderedDict(json.load(data_file))

length = (len(data["db"]["vendor"]["product"]))

for x in range(length):
    print(data["db"]["vendor"]["product"].values()[x]["price"]["dollars"])

Output is:

{u'1': 2, u'0': 8}
[10, 2]

The reason the output is different is that your fruits and vegetables are stored differently (one is a list and the other is a dictionary). You'll have to make them the same if you want to be able to iterate over them in a similar fashion.

Upvotes: 2

Anand Tripathi
Anand Tripathi

Reputation: 16136

I think the input string is wrong.

{
    "d": {
        "items": {
             "vegatables": {
                           "spinach": 120,12,23,3445
                           }
                 }
          }
}

JSON format doesn't has the the following input it must be changed to

{
    "d": {
        "items": {
             "vegatables": {
                           "spinach": [120,12,23,3445]
                           }
                 }
          }
}

Then the following command will work fine

print(data["d"]["items"]["vegatables"]["spinach"][0])

Upvotes: 0

Related Questions