Adding JSON values into a list
Solution 1
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']]
Solution 2
If you just want this
ips = [["custom3","modemId"],["custom3","modemId"]]
Then all you need is a simple list comprehension
ips = [d.keys() for d in json1_obj['data']]
If you want to actually get the values (in order), not the keys
ips = [ [ d['custom3'], d['modemId'] ] for d in json1_obj['data']]
juiceb0xk
Updated on June 04, 2022Comments
-
juiceb0xk almost 2 years
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?
-
juiceb0xk almost 7 yearsThis worked! Thank you very much. Very interesting indeed, I was just stuck on adding the two values into a list.
-
juiceb0xk almost 7 yearsThis is handy indeed, unfortunately, my JSON objects hold a lot more data than what I had specified, sorry about that! Printing my list prints every single value. I only need two values from my JSON objects.
-
OneCricketeer almost 7 yearsYou could do the same in one line ;)