First, the difference between the two
json.dumps () is used to convert a string dictionary format
son.loads () is used to convert the string dictionary format
JSON Import diction = { "name": "AA", "phonenumber": 13,305,958,697,865, "Grade": "3class"} Print (diction) # original file format dictionary d1 = json.dumps (diction) # dictionary to convert string Print (D1) D2 = json.loads (D1) to convert a string dictionary # Print (D2) Print ( 'D', type (diction)) Print ( 'D1', type (D1)) Print ( ' d2 ', type (d2))
Output:
{'phonenumber': 13305958697865, 'grade': '3class', 'name': 'aa'} {"phonenumber": 13305958697865, "grade": "3class", "name": "aa"} {'phonenumber': 13305958697865, 'grade': '3class', 'name': 'aa'} d <class 'dict'> d1 <class 'str'> d2 <class 'dict'>
Second, note
When the type of error will dict json file data is written, you need to first convert the string format type dict rewrite json file. We need to use json.dumps ()
Open with ( 'd3.json', 'W', encoding = 'UTF-. 8') AS F: f.write (json.dumps (diction)) # write the same character string as a dict through json.dumps () Conversion the json file f.close ()
View d3.json contents of the file:
{"phonenumber": 13305958697865, "name": "aa", "grade": "3class"}