通过Python读写JSON

2024-05-17 10:56:09 发布

您现在位置:Python中文网/ 问答频道 /正文

read.json文件:

{
    "Username" : "admin",
    "Password" : "admin",
    "Iterations" : 5,
    "Decimal" : 5.5,
    "tags" : ["hello", "bye"],
    "Value" : 5
}

program.py文件:

import json 
with open('read.json') as data_file:
    data = json.load(data_file)

data = str(data)
data.replace("'",'""',10)
f = open("write.json", "w")
f.write(data)

write.json文件:

{'Username': 'admin', 'Password': 'admin', 'Iterations': 5, 'Decimal': 5.5, 'tags': ["hello", "bye"], 'Value': 5}

我想实现的目标:

  1. 从Read.JSON文件读取JSON数据
  2. 在我的程序中解析和修改JSON中的一些值
  3. 写入另一个Write.json文件(json格式)

我的代码中没有错误,但是write.json不包含双引号(“”)中的值,而是用单引号包装的值,这使得它不是一个正确的json格式。

要使write.json文件包含正确的json格式,还要对write.json文件进行“漂亮的写入”,需要做哪些更改。


Tags: 文件jsonhelloreaddataadmin格式tags
2条回答

可以直接将json数据转储到文件中。Docs

import json
with open('read.json', 'w') as outfile:
    json.dump(data, outfile, sort_keys=True, indent=4)
    # sort_keys, indent are optional and used for pretty-write 

要从文件读取json,请执行以下操作:

with open('read.json') as data_file:    
    data = json.load(data_file)

问题是,您正在使用python表示将字典转换为字符串,该表示更喜欢简单的引号。

正如Vikash所说,不需要转换成字符串(您正在丢失结构)。更改数据,然后让json.dump处理dict-to-text过程,这一次是遵循json格式,并使用双引号。

您的问题是提到“预处理”输出,您可以通过向json.dump添加额外的参数来实现这一点

data["Username"] = "newuser"  # change data

with open("write.json", "w") as f:
    json.dump(data,f,indent=4,sort_keys=True)

现在文件内容是:

{
    "Decimal": 5.5,
    "Iterations": 5,
    "Password": "admin",
    "Username": "newuser",
    "Value": 5,
    "tags": [
        "hello",
        "bye"
    ]
}
  • indent:选择缩进级别。具有“预处理”输出的良好效果
  • sort_keys:如果设置了,密钥将按字母顺序排序,这将保证每次都有相同的输出(python密钥顺序是随机的)

相关问题 更多 >