-1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
thamuppet
  • 75
  • 5
  • 1
    `data['site1'][0]['sw3'] = {...}`… Not that this makes a whole lot of sense. Why is `site1` a list in the first place, if apparently you only expect to have exactly one object in it? – deceze May 10 '22 at 10:21
  • As I wrote in the post. It was an example to show the issue The plan with the JSON-file is different than the example. No, this doesn't make much sense I agree. – thamuppet May 10 '22 at 10:49

1 Answers1

1

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.

Effi Hol
  • 71
  • 6
  • Thanks for your response. I'm afraid I don't get this. 'sw3' is not in the JSON-file and therefore I'm getting a KeyError when doing this. 'sw3' is part of the new_data to append. I might be missing something obvious here? – thamuppet May 10 '22 at 10:38
  • I edit my previous comment, I just specify the name of the key and give it the value. Now it should work for you. You don't need the append part. – Effi Hol May 10 '22 at 10:59