Home > Software design >  How to append to json object
How to append to json object

Time:08-29

I have the following code to create a JSON file from all my cisco devices in the company. All devices have either 2021 or 2022 in their name. so I have 2 loops to count them all and save as json file:

json_object = {}
for i in idf:
    for device in data:
        if "2021" in device and device[-4:].isdigit():
            if device[-4:-2] == i:
                json_object[i] = {'2021': device }

        if "2022" in device and device[-4:].isdigit():
            if len(device) >= 18:
                if device[:-2].isdigit():
                    if device[:-2] == i:
                        json_object[i] = {'2022': device }


        print(json_object)

The problem is, it only saves the last iterate in the loop. It is finding all devices, but it is replacing the items in the JSON object. I need to APPEND the data for each LOOP

How can I do that?

CodePudding user response:

Maybe try something like this? I have added a comment at the end of each added/modified line.

json_object = {}
for i in idf:
    json_objects[i] = []  # line added
    for device in data:
        if "2021" in device and device[-4:].isdigit():
            if device[-4:-2] == i:
                json_object[i]  = [{'2021': device }]  # line modified

        if "2022" in device and device[-4:].isdigit():
            if len(device) >= 18:
                if device[:-2].isdigit():
                    if device[:-2] == i:
                        json_object[i]  = [{'2022': device }]  # line modified

The idea is that, for each i, you will want to create a list in which you will add your values. For each iteration, you append to that list by doing json_object[i] = ....

Hope this helps!

CodePudding user response:

You could use setdefault to do that:

json_object = {}
for i in idf:
    for device in data:
        if "2021" in device and device[-4:].isdigit():
            if device[-4:-2] == i:
                json_object.setdefault(i, []).append({'2021': device })

        if "2022" in device and device[-4:].isdigit():
            if len(device) >= 18:
                if device[:-2].isdigit():
                    if device[:-2] == i:
                        json_object.append({'2022': device })
  • Related