[英]How to write python list containing pairs in a JSON file in a custom format?
I have a list named name_class
containing pairs of names and labels respectively like ['2_255.png', 255], ['1_256.png', 256], ['2_257.png', 257]
.我有一个名为
name_class
的列表, name_class
包含名称和标签对,如['2_255.png', 255], ['1_256.png', 256], ['2_257.png', 257]
。 Now I want to write a json file with the following structure现在我想写一个具有以下结构的json文件
{
"names": [
["2_255.png",255],
["1_256.png",256],
["1_257.png",257]
]
}
So far my code is like below到目前为止,我的代码如下
with open(json_file_name, 'w') as outfile:
json.dumps(name_class, outfile, indent=1)
Which produces其中产生
[
[
"2_255.png",
255
],
[
"1_256.png",
256
],
[
"1_257.png",
257
]
]
How can I get the desired output?如何获得所需的输出?
You almost got it right, this should work:你几乎做对了,这应该有效:
json_object = { 'names': name_class }
with open(json_file_name, 'w') as outfile:
json.dump(json_object, outfile, indent=1)
To bind each of these to a dictionary entry with name "names":要将其中的每一个绑定到名为“names”的字典条目:
with open("json.json", 'w') as outfile:
outfile.write(json.dumps({"names": name_class}, indent=1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.