假设我有一个包含以下内容的 file.json:
[
{
"name": "Shirt1",
"product_id": "001234"
},
{
"name": "Shirt2",
"product_id": "005678"
}
]
使用 Python3,我想向两个词典中添加以下行:
"type": "external"
"reviews_allowed": false
这是我的代码:
import json
import os
with open("file.json", "r", encoding="utf8") as in_file:
INP = json.load(in_file)
DATA = []
for item in INP:
item["type"] = "external"
item["reviews_allowed"] = "false"
DATA.append(item)
with open("file2.json", "w", encoding="utf-8") as out_file:
out_file.write(json.dumps(DATA, indent=2, ensure_ascii=False))
os.rename("file2.json", "file.json")
但是,我得到以下信息:
[
{
"name": "Shirt1",
"product_id": "001234",
"type": "external",
"reviews_allowed": "false"
},
{
"name": "Shirt2",
"product_id": "005678",
"type": "external",
"reviews_allowed": "false"
}
]
有没有办法去掉 false 周围的双引号? 非常感谢您抽出时间!
请您参考如下方法:
false 是 recognised作为它自己的 JSON 类型:
A value can be a string in double quotes, or a number, or
trueorfalseornull, or an object or an array.
在 python 中,JSON false 直接映射到 False bool 值:
>>> json.dumps({'val' : False})
'{"val": false}'
