How to write dictionary contents to json file in python
This article mainly introduces the relevant knowledge of "how to write dictionary content into json file in python". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to write dictionary content into json file in python" can help you solve the problem.
How python writes the contents of the dictionary to the json file: we can first convert the dictionary to a string using the json.dumps () function, and then write the contents to json. The json.dumps () function is responsible for encoding the data.
When the contents of the dictionary are written to json, you need to use json.dumps to convert the dictionary to a string before writing it.
Json also supports formatting, and indentation can be set through the parameter indent. If it is not set, it will be saved on one line.
For example:
No indentation:
From collections import defaultdict, OrderedDictimport jsonvideo = defaultdict (list) video ["label"] .append ("") video ["data"] .append ["score"] .append (0.3) video ["label"] .append ("xixi") video ["data"] .append video ["score"] .append test_dict = {'version': "1.0',' results': video, 'explain': {' used': True 'details': "this is for josn test",}} json_str = json.dumps (test_dict) with open (' test_data.json', 'w') as json_file: json_file.write (json_str)
Indent:
From collections import defaultdict, OrderedDictimport jsonvideo = defaultdict (list) video ["label"] .append ("") video ["data"] .append ["score"] .append (0.3) video ["label"] .append ("xixi") video ["data"] .append video ["score"] .append test_dict = {'version': "1.0',' results': video, 'explain': {' used': True 'details': "this is for josn test",}} json_str = json.dumps (test_dict, indent=4) with open (' test_data.json', 'w') as json_file: json_file.write (json_str)
This is the end of the introduction on "how to write dictionary contents to json files in python". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.