Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JSON values into a list

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?

like image 797
juiceb0xk Avatar asked Feb 16 '26 21:02

juiceb0xk


1 Answers

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']]
like image 60
Pietro Tortella Avatar answered Feb 19 '26 10:02

Pietro Tortella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!