使用 Python 写入 JSON 文件

Issue writing to JSON-file with Python

JSON-文件

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

代码:

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)

结果:

{
  "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"
      }
    }
  ]
}

Python/JSON 的新手,尽力而为。

对题。 如何使它附加到与 sw1 和 sw2 相同的结构中? 意思是,我现在多了一个不需要的 '},{'

示例只是为了展示问题,而不是实际代码。

将您的代码更改为:

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

因为现在你指定了把字典放在哪里。