1

I have created my own json data with an array I would like to parse into a python list. However, I've been having trouble doing so.

How can I extract my json array into a python list?

json data:

[
  {
    "ip": "192.168.241.109", 
    "cameras": 
       {
          "front": "nf091", 
          "inside": "nf067", 
          "right": "004317",
          "rear": "000189",
          "left": "nf084"
       }
  }, 
  {
   "ip": "192.168.241.110",           
   "cameras": 
   {
          "front": "nf091", 
          "inside": "nf067", 
          "right": "004317", 
          "rear": "000189", 
          "left": "nf084"
   }
  }
]

My json data is valid, so I don't know why I'm having trouble with the below code:

system_json = open(json_file)
json_obj = json.load(system_json)

camera_details = [[i['front'], i['rear'], i['left'], i['right'], i['inside']] for i in json_obj['cameras']]

The above code snippet does not work as it yields the list indices must be integers, not str error.

What am I doing wrong, and how can I properly parse my json array into a python list?

1 Answer 1

7

The issue is that your JSON "object" is a list, but then you try to index into it with a string (json_obj['cameras']).

What you have is a JSON array, each element of which is a dictionary containing (among other things) a key called "cameras". I believe this code does what you want:

import json

text = """[{"ip": "192.168.241.109", "cameras": {"front": "nf091", "inside": "nf067", "right": "004317", "rear": "000189", "left": "nf084"}}, {"ip": "192.168.241.110", "cameras": {"front": "nf091", "inside": "nf067", "right": "004317", "rear": "000189", "left": "nf084"}}]"""

json_array = json.loads(text)

camera_details = [[i['cameras']['front'], i['cameras']['rear'], i['cameras']['left'], i['cameras']['right'], i['cameras']['inside']] for i in json_array]
print(camera_details)

# Output:
# [['nf091', '000189', 'nf084', '004317', 'nf067'], ['nf091', '000189', 'nf084', '004317', 'nf067']]

EDIT

Possibly clearer/easier?

camera_details = [
    [
        cameras["front"],
        cameras["rear"],
        cameras["left"],
        cameras["right"],
        cameras["inside"],
    ]
    for cameras in [item["cameras"] for item in json_array]
]
Sign up to request clarification or add additional context in comments.

Comments

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.