简体   繁体   中英

How can I iterate through JSON values using Python?

My JSON data looks like this:

{
    "cameras": [
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000287"
        },
        {
            "item": "810-00022",
            "name": "rear",
            "serial": "000166"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000492"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000282"
        },
        {
            "item": "810-00022",
            "name": "inside",
            "serial": "000143"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:16",
    "name": 1623,
    "serial": "000408"
}
{
    "cameras": [
        {
            "item": "810-00032",
            "name": "inside",
            "serial": "000007"
        },
        {
            "item": "810-00022",
            "name": "right",
            "serial": "000941"
        },
        {
            "item": "810-00022",
            "name": "front",
            "serial": "000637"
        },
        {
            "item": "810-00022",
            "name": "left",
            "serial": "000430"
        }
    ],
    "item": "810-00023",
    "mac": "14:1f:ba:90:01:9e",
    "name": 1599,
    "serial": "000309"
}

How can I output the names (not camera names) for each of my entries?

In theory, I want to be able to print the following 1623 and 1599 .

I have the following, but it is not working for some reason:

json2 = open('C:\\Users\\' + comp_name + '\\Documents\\Python Firmware Script\\curl\\src\\systemidsout.json')
json2_obj = json.load(json2)

for i in json2_obj[]:
     print i['name']

I was hoping the above works, as it has for my other JSON file, but I'm guessing because the layout may be different, it's not working.

How can I output the 'name' values within my JSON file?

Furthermore, as a bonus question, how can I output the individual names within my camera array also?

If you change for i in json2_obj[]: to i in json2_obj: , it will work. If you want to output the individual names within a camera array, use

for j in i['cameras']:
    print(j['name'])

with in your for loop.

Just to mention, your JSON data has actually 2 JSON. If you want to read them from one file, you might want to change it to [{...},{...}] format. Otherwise, json.load() may raise an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM