【问题标题】:Reading and Writing JSON through Python通过 Python 读写 JSON
【发布时间】:2017-08-21 07:54:35
【问题描述】:

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 文件的“漂亮写入”。

【问题讨论】:

  • 您应该修改从json.load() 调用收到的data(将是dict),并使用json.dump() 将其写回文件。无需在两者之间使用str()
  • 你的 json 看起来不错(我从我这边检查),只需将 json.load(data) 更改为 json.loads(data)
  • @quamrana 你是对的 loads() 需要 str 不是文件 .json

标签: python json


【解决方案1】:

您可以直接将 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)

【讨论】:

    【解决方案2】:

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

    正如 Vikash 的回答所说,无需转换为字符串(您正在丢失结构)。更改您的数据,然后让json.dump 处理 dict 到文本的过程,这一次尊重 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按键顺序是随机的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 2021-06-04
      • 2022-01-06
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多