读写json文件

时间:2018-11-22 20:02:34

标签: python json

我正在PYTHON中进行一个项目,我需要在JSON文件中进行读写操作。

JSON文件的内容如下:

{
  "buildings": [
    {
      "name": "Trump Towers",
      "nr": "1",
      "worth": "399"
    },
    {
      "name": "Penning Towers",
      "nr": "2",
      "worth": "299"
    }
  ],
  "staff": [
    {
      "name": "D Trump",
      "nr": "1",
      "worth": "399"
    },
    {
      "name": "Mr Henry",
      "nr": "2",
      "worth": "299"
    }
  ]
}

同样,我需要能够读取,添加和删除单个建筑物和工作人员的数据

(以下内容并非正确的语法,但这是我要问的原因,我需要与此一起提供帮助)

(语法不准确),例如。

>>> read name of building nr 1
Trump Towers

>>> delete 'Trump Towers' from buildings (output to the file)
{
  "buildings": [
    {
      "name": "Penning Towers",
      "nr": "2",
      "worth": "299"
    }
  ],
  "staff": [
    {
      "name": "D Trump",
      "nr": "1",
      "worth": "399"
    },
    {
      "name": "Mr Henry",
      "nr": "2",
      "worth": "299"
    }
  ]
}

>>> set 'Penning Towers' from buildings nr to 1
{
  "buildings": [
    {
      "name": "Penning Towers",
      "nr": "1",
      "worth": "299"
    }
  ],
  "staff": [
    {
      "name": "D Trump",
      "nr": "1",
      "worth": "399"
    },
    {
      "name": "Mr Henry",
      "nr": "2",
      "worth": "299"
    }
  ]
}

>>> add 'Jake' with nr '3' and worth  '999' to staff

{
  "buildings": [
    {
      "name": "Penning Towers",
      "nr": "1",
      "worth": "299"
    }
  ],
  "staff": [
    {
      "name": "D Trump",
      "nr": "1",
      "worth": "399"
    },
    {
      "name": "Jake",
      "nr": "2",
      "worth": "299"
    },
    {
      "name": "Mr Henry",
      "nr": "3",
      "worth": "999"
    }
  ]
}

2 个答案:

答案 0 :(得分:1)

您可以使用json模块将json.load()的文件加载到Python字典中:

import json

f = open('file.json', 'r')
d = json.load(f)

一旦它是python dict,就可以根据需要对其进行修改。

然后您可以使用json.dump(d)

将json写入文件

答案 1 :(得分:1)

您可以使用json library从文件中将json作为python dict加载,然后修改该json并将其保存为文件。

import json

# Open json file and load its content as python dict
file = open('data.json', 'r')
my_json = json.loads(file.read())
file.close()

# Do stuff with that json
del my_json['buildings'][0]
my_json['buildings'][0]['Penning Towers'] = 1
my_json['staff'].append({'name': 'Jake', 'nr': '3', 'worth': '299'})

# Override json file with modified json
file = open('data.json', 'w')
file.write(json.dumps(my_json, indent=4))
file.close()
运行我们的代码后

data.json:

{
    "staff": [
        {
            "nr": "1",
            "worth": "399",
            "name": "D Trump"
        },
        {
            "nr": "2",
            "worth": "299",
            "name": "Mr Henry"
        },
        {
            "nr": "3",
            "worth": "299",
            "name": "Jake"
        }
    ],
    "buildings": [
        {
            "nr": "1",
            "worth": "299",
            "name": "Penning Towers"
        }
    ]
}