S Andrew
S Andrew

Reputation: 7198

How to extract data from json file in python

I have a below json config file in a project.

"Jackets": [
    {
        "GreenHSV": [30, 150, 72, 80, 255, 255]

    },
    {
        "OrangeHSV": [0, 150, 72, 25, 255, 255]

    }
]

I have to get the each value of GreenHSV (30, 150, 72, 80, 255, 255) and OrangeHSV 0, 150, 72, 25, 255, 255 in python code, keeping in mind that in future another HSV can be added like below

{
    "RedHSV": [0, 150, 72, 25, 255, 255]

}

so the code should be able to read RedHSV values as well without making any changes in the code. In above JSON, Jackets is basically a list which contains dict of list (if I am not wrong). To get each color HSV value, my approach is below:

for i in range(len(config["Jackets"])):
    print(config["Jackets"][i])
    hsv_dict = config["Jackets"][i]
    print(hsv_dict.keys())
    name = hsv_dict.keys()
    hsv_color_name = hsv_dict[name]
    print(hsv_color_name[0], hsv_color_name[1], hsv_color_name[2])
    print(hsv_color_name[3], hsv_color_name[4], hsv_color_name[5])

My approach is to first put a for loop with the range of len of Jackets so that if in future, new color is added, it will loop 3 times.

After that I have extracted the hsv_dict which contains this value {'GreenHSV': [30, 150, 72, 80, 255, 255]}. Now at this point I though I should get the key name of the dict as it will be GreenHSV or any next color, so that I can extract its value which will be list ([30, 150, 72, 80, 255, 255]) and then I can get the list values easily. But looks like my approach is wrong.

Can anyone please guide me. Thanks

Upvotes: 1

Views: 101

Answers (2)

Orestis Zekai
Orestis Zekai

Reputation: 922

hsv_dict.keys() returns a dict_keys object, so you should convert it to a list like so:

 list(hsv_dict.keys())

Since this is a list you can get the 0th argument like this:

list(hsv_dict.keys())[0]

This contains your key value

Upvotes: 1

Kemp
Kemp

Reputation: 3649

hsv_dict = config["Jackets"][i]

when i is 0 will cause hsv_dict to contain {'GreenHSV': [30, 150, 72, 80, 255, 255]}.

The problem in your code is that after name = hsv_dict.keys(), name contains a dict_keys object that will yield all of the keys.

You need to extract the first key, which requires something like

name = list(hsv_dict.keys())[0]

I'm not sure why you're using a list of dictionaries that only have one entry each though. I feel like the following would be an easier and more concise layout:

"Jackets":  {
    "GreenHSV": [30, 150, 72, 80, 255, 255],
    "OrangeHSV": [0, 150, 72, 25, 255, 255]
}

Upvotes: 1

Related Questions