1. The difference between
()
It is a string that serializes Python objects into JSON format. If you want to write JSON data to a file, you can()
The generated string is written to the file, or more directly()
function, it will serialize Python objects to the file directly.
The following are two methods, one is to use()
Then write the file, the second is to use()
Write directly to the file.
2. Use () and then write to the file
import json data = {"name": "Alice", "age": 30, "is_student": False} # Serialize to JSON stringjson_str = (data, indent=4) # Write a JSON string to a filewith open('', 'w', encoding='utf-8') as file: (json_str)
3. Use () to write directly to the file
import json data = {"name": "Alice", "age": 30, "is_student": False} # Write JSON data directly to a filewith open('', 'w', encoding='utf-8') as file: (data, file, indent=4)
4. () Parameters
fp
: File object, indicating the file to be written.-
indent
: Specify the indentation level to make the result more readable. IfNone
, then compact output; if it is an integer, it represents the number of spaces indented per layer; if it is a string, it is used for indentation per layer. -
ensure_ascii
: IfTrue
, all non-ASCII characters will be escaped as\uXXXX
Form. The default value isTrue
。 -
sort_keys
: Boolean value, indicating whether the dictionary keys are sorted alphabetically. -
separators
: Tuple, specifying the item separator and key-value separator.
import json data = {"name": "Alice", "age": 30, "languages": ["English", "French"], "is_student": False} with open('', 'w', encoding='utf-8') as file: (data, file, indent=4, ensure_ascii=False, sort_keys=True)
The parameters of () can be seen in the blog's parameters
This is the end of this article about the difference between python. For more related python and content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!