简体   繁体   中英

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] . Now I want to write a json file with the following structure

{
    "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":

with open("json.json", 'w') as outfile:
    outfile.write(json.dumps({"names": name_class}, indent=1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM