Python的读取JSON文件,并修改

问题描述 投票:35回答:3

嗨,我想从一个JSON文件获取数据,插入和id然后执行POST REST。我的文件data.json有:

{
    'name':'myname'
}

我想,这样的JSON数据看起来像添加ID:

 {
     'id': 134,
     'name': 'myname'
 }

所以我想:

import json
f = open("data.json","r")
data = f.read()
jsonObj = json.loads(data)

我无法加载JSON格式文件。我应该怎么做,这样我可以转换成JSON文件成JSON对象,并添加价值的另一个ID。

python json file-io
3个回答
59
投票

使用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

32
投票

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)

2
投票

我想提出瓦迪姆的解决方案的修改版本。它有助于处理异步请求写入/修改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)

0
投票

真的是有不少方法可以做到这一点,以上所有都在这样或那样的方式有效...让我补充一个简单的命题。因此,假如你目前现有的JSON文件看起来是这样的....

{
     "name":"myname"
}

而你要在这个新的JSON内容带来(添加键“ID”)

{
     "id": "134",
     "name": "myname"
 }

我的做法一直是保持代码容易跟踪的逻辑,可读性强。因此,首先,我们看整个现有的JSON文件到内存中,假设你很清楚地知道你的JSON现有的密钥(或多个)。

import json 

# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' #  assuming same directory (but you can work your magic here with os.)

# read existing json to memory. you do this to preserve whatever existing data. 
with open(PATH_TO_JSON,'r') as jsonfile:
    json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'

接下来,我们再次使用“开放()”的语法,用“W”选项。 “W”是写模式,可让我们编辑并写入新的信息的文件。下面就为我们的工作:::具有相同的目标写名称的任何现有的JSON将被自动删除的渔获物。

所以,我们现在能做的,仅仅是写相同的文件名与新数据

# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"

with open(PATH_TO_JSON,'w') as jsonfile:
    json.dump(json_content, jsonfile, indent=4) # you decide the indentation level

和你去那里! data.json应该是好去一个良好的老POST请求

© www.soinside.com 2019 - 2024. All rights reserved.