0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting the following error: string indices must be integers when I use the following for i in json2_obj: print i['name']
Nevermind, I fixed the formatting of my JSON and it now works. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.