pythonjsonappendindentationwritetofile

Issue writing to JSON-file with Python


The JSON-file

{
  "site1": [
    {
      "sw1": {
        "device_type": "cisco_ios",
        "host": "sw1.test.local"
      },
      "sw2": {
        "device_type": "cisco_ios",
        "host": "sw2.test.local"
      }
    }
  ]
}

The Code:

import json


def write_json(data, filename='data.json'):
    with open(filename, "w") as f:
        json.dump(data, f, indent=2)


def collect_new_data():
    with open('data.json') as json_file:
        data = json.load(json_file)
        temp = data['site1']
        new_data = {'sw3': {"device_type": "cisco_ios", "host": "sw3.tpo.local"}}
        temp.append(new_data)
        return data


the_data = collect_new_data()
write_json(the_data)

The outcome:

{
  "site1": [
    {
      "sw1": {
        "device_type": "cisco_ios",
        "host": "sw1.test.local"
      },
      "sw2": {
        "device_type": "cisco_ios",
        "host": "sw2.test.local"
      }
    },
    {
      "sw3": {
        "device_type": "cisco_ios",
        "host": "sw3.tpo.local"
      }
    }
  ]
}

New to Python/JSON, trying my best.

To the question. How do I make it so that it appends in the same structure as sw1 and sw2? Meaning, I now get an extra unwanted '},{'

Examples is just to show the issue, not the actual code.


Solution

  • Change your code to this:

    data['site1'][0]['sw3'] = {"device_type": "cisco_ios", "host": "sw3.tpo.local"}
    

    Because now you specify where to put the dict exactly.