How to convert json to string by python
This article mainly explains "how python converts json into strings". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how python converts json into a string.
The way to convert json to a string in python: first print out the type of data, then enter the "str = json.dumps (data,indent=2)" command to convert json to a string, and finally print the string using the print statement.
Import jsondata = [{"name": "Tom", "gender": "male"}, {"name": "Jack", "gender": "male"}] # convert the json format to a string print (type (data)) str = json.dumps (data, indent=2) # indent=2 according to the indentation format print (type (str)) print (str) # save to the json format file with open ('data.json', 'w') Encoding='utf-8') as file: file.write (json.dumps (data, indent=2, ensure_ascii=False)) # ensure_ascii=False can eliminate the garbled problem of json containing Chinese characters
Running result:
Not adding ensure_ascii=False will lead to garbled code.
[{"name": "Tom", "gender": "male"}, {"name": "\ u6770\ u514b", "gender": "\ u7537"}]
Contents of data.json file:
Add ensure_ascii=False
[{"name": "Tom", "gender": "male"}, {"name": "Jack", "gender": "male"}] so far, I believe you have a better understanding of "how python converts json into a string". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!