Python读取JSON文件并进行修改

cod*_*rer 40 python file-io json

嗨,我正在尝试从json文件中获取数据并插入和id然后执行POST REST.我的文件data.json有:

{
    'name':'myname'
}
Run Code Online (Sandbox Code Playgroud)

我想添加一个id,以便json数据看起来像:

 {
     'id': 134,
     'name': 'myname'
 }
Run Code Online (Sandbox Code Playgroud)

所以我尝试过:

import json
f = open("data.json","r")
data = f.read()
jsonObj = json.loads(data)
Run Code Online (Sandbox Code Playgroud)

我无法加载json格式文件.我应该怎么做才能将json文件转换为json对象并添加另一个id值.

fal*_*tru 62

使用设置项目data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part
Run Code Online (Sandbox Code Playgroud)

  • 无关:json格式是为Unicode文本定义的.您可以使用`with codecs.open('data.json','r +',encoding ='utf-8')作为f` (7认同)

Vad*_*lov 34

falsetru的解决方案很好,但有一个小错误:

假设原始'id'长度大于5个字符.当我们使用新的'id'(134只有3个字符)进行转储时,从文件中的位置0写入的字符串的长度比原始长度.来自原始内容的文件中留有额外字符(例如'}').

我通过替换原始文件解决了这个问题.

import json
import os

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.

os.remove(filename)
with open(filename, 'w') as f:
    json.dump(data, f, indent=4)
Run Code Online (Sandbox Code Playgroud)

  • 删除和重新创建文件可能会导致权限问题。 (3认同)
  • 当您可以覆盖整个内容时,为什么需要删除文件? (2认同)

Vad*_*sko 9

我想介绍 Vadim 解决方案的修改版本。它有助于处理写入/修改 json 文件的异步请求。我知道这不是原始问题的一部分,但可能对其他人有帮助。

在异步文件修改的情况下,如果请求频繁出现,os.remove(filename)则会引发FileNotFoundError。为了克服这个问题,您可以创建具有修改内容的临时文件,然后同时重命名替换旧版本。此解决方案适用于同步和异步情况。

import os, json, uuid

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    # add, remove, modify content

# create randomly named temporary file to avoid 
# interference with other thread/asynchronous request
tempfile = os.path.join(os.path.dirname(filename), str(uuid.uuid4()))
with open(tempfile, 'w') as f:
    json.dump(data, f, indent=4)

# rename temporary file replacing old file
os.rename(tempfile, filename)
Run Code Online (Sandbox Code Playgroud)