How to realize the conversion between dictionary and json in python
This article mainly introduces the relevant knowledge of how to realize the conversion between dictionary and json in python, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on how to convert dictionary and json in python. Let's take a look.
The operating environment of this tutorial: windows7 system, Python 3.9.1 Dell G3 computer.
1. Convert the dictionary to json
Use json.dumps
Json.dumps is to encode python objects into json objects, and you can convert dictionaries into json strings.
Method format
# Dictionary converted to json string json.dumps (dict)
Example
# create a dictionary info_dict = {'name':' Joe', 'age': 20,' job': 'driver'} # dumps convert the data into a string info_json = json.dumps (info_dict,sort_keys=False, indent=4, separators= (',',:)) # display the data type print (type (info_json)) f = open ('info.json', 'w') f.write (info_json)
2. Json to dictionary
Use json.loads
Json.loads is to decode json objects into python objects, that is, to convert dictionary-type data into json strings.
Method format
# json string conversion to dictionary json.loads (json_str)
Use an example
In [25]: J Out [25]:'{"name": "mary", "age": 21}'In [26]: result = json.loads (j) In [27]: result Out [27]: {'name':' mary', 'age': 21} In [28]: type (result) Out [28]: dict's article on "how to convert dictionaries into json in python" ends here. Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to convert dictionaries to json in python". If you want to learn more, you are welcome to follow the industry information channel.