The python method to write dictionary content to json file: we can first use the () function to convert the dictionary to a string; then just write the content to json. The () function is responsible for encoding the data.
When writing dictionary content to json, you need to convert the dictionary to a string and then write it.
json also supports formatting, through the parameter indent can be set to indent, if not set, then saved will be a line.
Examples:
No indentation:
from collections import defaultdict, OrderedDict import json video = defaultdict(list) video["label"].append("haha") video["data"].append(234) video["score"].append(0.3) video["label"].append("xixi") video["data"].append(123) video["score"].append(0.7) test_dict = { 'version': "1.0", 'results': video, 'explain': { 'used': True, 'details': "this is for josn test", } } json_str = (test_dict) with open('test_data.json', 'w') as json_file: json_file.write(json_str)
There are indentations:
from collections import defaultdict, OrderedDict import json video = defaultdict(list) video["label"].append("haha") video["data"].append(234) video["score"].append(0.3) video["label"].append("xixi") video["data"].append(123) video["score"].append(0.7) test_dict = { 'version': "1.0", 'results': video, 'explain': { 'used': True, 'details': "this is for josn test", } } json_str = (test_dict, indent=4) with open('test_data.json', 'w') as json_file: json_file.write(json_str)
Above is python will write the contents of the dictionary into the json file of the example code in detail, more about python how to write the contents of the dictionary into the json file of information please pay attention to my other related articles!