I'm wanting to iterate through my JSON file, and add two values into a list.
In theory, I'm wanting to have a nested list as: ips = [["custom3","modemId"],["custom3","modemId"]] and so on. My JSON file has 171 of each custom3 and modemId values. So in theory my nested list will contain 171 lists.
I'm having trouble adding the values into a list, in which I would like to append each list together, to create 171 lists.
json1 = open('C:\\Users\\' + comp_name + '\\Documents\\Programming Projects\\Python\\Python Firmware Script\\curl\\src\\out.json')
json1_obj = json.load(json1)
for i in json1_obj['data']:
ip = [i['custom3']['modemId']]
A snippet of my JSON data:
{
"data": [
{
"custom3": "192.168.243.132",
"modemId": "000408"
},
{
"custom3": "192.168.244.156",
"modemId": "000310"
}
]
}
I have 171 objects as above, but I'm only showing two. From the above, I would like to create two lists and append them each into a nested list.
How do I iterate through each JSON object and create a nested list with my JSON data in Python?
As mentioned in the comments, once loaded the json is a python dictionary. You should now iterate on the value of the 'data' key, extract the information and store them in a list.
Something like this should do the job:
json_obj = json.load(json1)
ips = []
for piece in json_obj['data']:
this_ip = [piece['custom3'], piece['modemId']]
ips.append(this_ip)
One line form:
ips = [[piece['custom3'], piece['modemId']] for piece in json_obj['data']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With