[英]Python json How to add data
I don't speak English well So the question may be a bit odd我英语说得不好所以这个问题可能有点奇怪
{
"arg1": {
"1": "1",
"2": "2"
},
"arg2": {
"1": "1",
"2": "2"
},
"arg3": {
"1": "1",
"2": "2"
}
}
I want to store data this way.我想以这种方式存储数据。 What should I do?
我应该怎么办?
json_data = {arg3: {"1": "1", "2": "2"}}
with open(f'./Json/test.json', 'w', encoding='utf-8') as make_file:
json.dump(json_data, make_file, ensure_ascii=False ,indent="\t")
Is this right?这是正确的吗? I would appreciate it if you let me know.
如果您让我知道,我将不胜感激。
I don't know what to do by deleting the original content.我不知道删除原始内容该怎么办。
Your code works fine.您的代码工作正常。 The only problem I see when your running it is that that
arg3
needs to be written as "arg3"
in double quotes (single quotes are invalid in json) unless you have a value for it defined previously.我在运行时看到的唯一问题是
arg3
需要用双引号写成"arg3"
(单引号在 json 中无效),除非您之前定义了它的值。
json_data = {"arg3": {"1": "1", "2": "2"}}
Make that change, and you should be able to load and properly display your JSON with:进行更改,您应该能够加载并正确显示您的 JSON :
with open(f'output.json') as f:
a = json.load(f)
print(json.dumps(a, indent="\t"))
If you do the json.dumps()
you get a properly formatted json which you can then call print
on to display.如果你执行
json.dumps()
你会得到一个格式正确的 json 然后你可以调用print
来显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.