1 Function introduction
Function name | Function description |
---|---|
() | Used fromFile Object Read JSON data in and parse it into a Python object. |
() | Used toJSON format strings Resolved as a Python object |
() | Used to serialize Python objects into JSON format,and write it to a file 。 |
() | Used to serialize Python objects intoJSON format strings 。 |
2 ()
()
It is a function provided by the json module in Python, used forFrom the file object
Read JSON data and parse it into a Python object.
2.1 Syntax format
(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Parameter description:
fp:
A support for a JSON document to perform deserialization.read()
text file or binary file.cls:
If this parameter is set, a custom JSON decoder is used. Any pass toload()
The redundant keyword arguments of the method are passed to the constructor of the cls. If None is passed in (default value), it will useJSONDecoder
。object_hook:
Optional function, if set, will be a function that takes any decoded object literal (i.e., a dict) as a parameter when called. The return value of this function will be used instead of the dict. This feature can be used to implement custom decoders, such as JSON-RPC class prompts. The default value is None.parse_float:
Optional function, if set, will be a function that takes a string representing each JSON floating point number to be decoded as a parameter when called. If None (default value), it is equivalent tofloat(num_str)
. This can be used to parse JSON floating point numbers into custom data types, for example.parse_int:
Optional function, if set, will be a function that takes a string representing each JSON integer to be decoded as an argument when called. If None (default value), it is equivalent toint(num_str)
. This can be used to parse JSON integers into custom data types, such as float.parse_constant:
Optional function, if set, will be a function with one of the following strings as parameters:-Infinity
,Infinity
orNaN
. This can be used to raise an exception when an invalid JSON number is encountered. The default value is None.object_pairs_hook:
Optional function, if set, will be a function that decodes arbitrary object literals as parameters when called with an ordered list of values. The return value of this function will be used instead of the dict. This feature can be used to implement custom decoders. If it is setobject_hook
,butobject_pairs_hook
The priority is higher, and the default value is None.
2.2 Exception description
JSONDecodeError:
When the deserialized data is not a legitimate JSON document.UnicodeDecodeError:
When deserialized data does not containUTF-8
,UTF-16
orUTF-32
Encoded data.
2.3 Return value description
() Returns a Python object, the specific type depends on the content of the JSON file:
JSON Objects
({})
Will be parsed into Pythondict
。
JSON array([])
Will be parsed into Pythonlist
。
JSON string("...")
Will be parsed into Pythonstr
。
JSON Numbers(123 or 12.3)
Will be parsed into Pythonint
orfloat
。
JSONtrue
、false
andnull
Will be parsed into PythonTrue
、False
andNone
。
2.4 Things to note
-
File encoding:
When opening the file, make sure to specify the correct encoding (e.g.utf-8
), otherwise the parsing may fail due to encoding problems. -
File path:
Make sure the file path is correct, otherwise it will be thrownFileNotFoundError
abnormal. -
The JSON format must be correct:
If the JSON file format is incorrect (such as missing quotes, mismatched brackets, etc.), it will be thrownabnormal.
-
Performance issues:
For very large JSON files,()
The entire file will be loaded into memory. If memory is limited, consider using streaming parsing tools (such as ijson).
2.5 Example
2.5.1 Sample Data
The file contents are as follows:
{ "name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"] }
2.5.2 Basic usage
import json # Open the file and read the JSON datawith open('', 'r', encoding='utf-8') as f: data = (f) print(data) # {'name': 'Chen Nan', 'age': 10028, 'skill': ['Encouraging Demon Sutra', 'Taishang Forgetful Love Record', 'Tiantian and Earth Magical Art']}print(type(data)) # <class 'dict'>
2.5.3 Custom parsing
import json def custom_parse_float(value): """ Custom floating point parsing functions :param value: Pass in floating point number :return:Return the value that retains one decimal """ return round(float(value), 1) # Keep a decimal # Open the file and read the JSON datawith open('', 'r', encoding='utf-8') as f: data = (f, parse_float=custom_parse_float) print(data) # {'name': 'Chen Nan', 'age': 10028.3, 'skill': ['Encoding Sutra', 'Taishang Forgetful Love Record', 'Tiantian and Earth Magical Art']}
3 ()
()
It is a function provided by the json module in Python.Used to parse strings in JSON format into Python objects
. JSON (JavaScript Object Notation) is a lightweight data exchange format that is often used for data transmission and configuration files.
3.1 Syntax format
(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Similar toload()
, but not for file-type objects, but use this conversion table to convert s (a JSON containingstr
,bytes
orbytearray
instance) deserialize to a Python object.
3.2 Return value description
() Returns a Python object, the specific type depends on the content of the JSON file:
JSON Objects
({})
Will be parsed into Pythondict
。
JSON array([])
Will be parsed into Pythonlist
。
JSON string("...")
Will be parsed into Pythonstr
。
JSON Numbers(123 or 12.3)
Will be parsed into Pythonint
orfloat
。
JSONtrue
、false
andnull
Will be parsed into PythonTrue
、False
andNone
。
3.3 Things to note
-
JSON strings must conform to the format:
If the JSON string format is incorrect (such as missing quotes, mismatched brackets, etc.), an exception will be thrown. -
Performance issues:
For very large JSON data, it is recommended to use() to read from the file stream instead of loading it into memory at once.
3.4 Example
3.4.1 Basic usage
import json # JSON format stringsjson_str = '{"name": "Chen Nan", "age": 10028.3, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"]}' # parse to Python dictionarydata = (json_str) print(data) # {'name': 'Chen Nan', 'age': 10028.3, 'skill': ['Encouraging Demon Sutra', 'Taishang Forgetful Love Record', 'Tiantian and Earth Magical Art']}print(type(data)) # <class 'dict'>
3.4.2 Custom parsing
import json # JSON format stringsjson_str = '{"name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"]}' # Custom floating point parsing functiondef custom_parse_float(value): """ Custom floating point parsing functions :param value: Pass in floating point number :return:Return the value that retains one decimal """ return round(float(value), 1) # Keep a decimal # parse JSON stringsdata = (json_str, parse_float=custom_parse_float) print(data) # {'name': 'Chen Nan', 'age': 10028.3, 'skill': ['Encouraging Demon Sutra', 'Taishang Forgetful Love Record', 'Tiantian and Earth Magical Art']}print(type(data)) # <class 'dict'>
3.4.3 Network Request
import requests import json # Dictionary type form parametersdata = {'Chen Nan': 'Climb out of the tomb of God', 'Chu Yue': 'One of Chen Nan's wife'} # Send a network requestres = ('/post', data=data) res_dict = () # Convert response data to dictionary typeprint(res_dict) print(type(res_dict))
4 ()
()
It is a function provided by the json module in Python.Used to serialize Python objects into JSON format and write them to a file
. Unlike (), () writes data directly to the file object instead of returning a string.
4.1 Syntax format
(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Parameter description:
obj:
The Python object to be serialized.fp:
The file-type object obj will be the target of serialized output. The json module is always generatedstr object, not bytes object, so () must support str input
。skipkeys:
If True, it is not a basic type(str,int,float,bool,None)
The key will be skipped without being triggeredTypeError
. Default is False.ensure_ascii:
If True (default), the output will ensure that all inputs areEscape non-ASCII characters
. If False, these characters will be output as is.check_circular:
If False, the loop reference check for container type will be skipped and the loop reference will causeRecursionError
(or worse). Default is True.allow_nan:
If False, the float value exceeds the range(nan,inf,-inf)
Doing a serialization will result in a ValueError to strictly follow the JSON specification. If True (default), their JavaScript equivalents will be used(NaN,Infinity,-Infinity)。
cls:
If set, rewrite to adefault()
A custom JSON encoder for method to serialize to custom data types. If None (default value), useJSONEncoder。
indent:
If it is a positive integer or string, the JSON array element and object member will be pressed byThe specified indentation level beautification printing
. Positive integers represent the specified number of spaces per level indentation; strings (such as "\t") are used for indentation per level. If it is a zero, a negative number, or "" (empty string), only newline characters are inserted. If None (default), the most compact representation is used.separators:
A binary: (item_separator, key_separator). If it is None (default value), then default when indent is Noneseparators are (',',':'), otherwise (',',':').
To use the most compact form of JSON, specify (',',':') to remove spaces.default:
Functions that will be called when the object cannot be serialized. It should return a JSON-encoded version or raise a TypeError. If None (default value), a TypeError will be raised.sort_keys:
If True, the dictionary output will be sorted by key. Default is False.
4.2 Return value description
() There is no return value, it will write the serialized JSON data directly to the file.
4.3 Things to note
-
File Mode:
When opening a file, make sure to use write mode(such as 'w')
, otherwise an error will be thrown. -
Non-string keys:
If the dictionary's key is not a string type, a TypeError will be thrown by default. Can be set byskipkeys=True
Skip these keys. -
Special values:
By default, special values such as NaN and Infinity can be serialized. If not required, you can set itallow_nan=False。
Performance issues:
For very large data, () will load the entire object into memory. If memory is limited, consider using streaming writing tools.
4.4 Example
4.4.1 Basic usage
import json # Python Dictionarydata = { "name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"] } # Open the file and write JSON datawith open('', 'w', encoding='utf-8') as f: (data, f)
4.4.2 Customized sequences
If a Python object contains a type that cannot be serialized directly (such as datetime), you can usedefault
The parameter specifies a processing function:
import json from datetime import datetime def custom_serializer(obj): """ Custom serialization functions :param obj: :return: """ # Determine whether the data is a date if isinstance(obj, datetime): return ('%Y-%m-%d %H:%M:%S') # Convert datetime to string raise TypeError("Type not serializable") # Python dictionary containing datetime objectdata = { "name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"], "created": () } # Open the file and write JSON datawith open('', 'w', encoding='utf-8') as f: (data, f, default=custom_serializer, indent=4, ensure_ascii=False)
5 ()
()
It is a function provided by the json module in Python.String for serializing Python objects into JSON format
. Unlike (), () returns a string instead of writing to a file directly.
5.1 Syntax format
(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Use this conversion table to serialize obj toJSON format str
. The meaning of its parameters is the same as that in dump().
5.2 Return value description
() Returns a string in JSON format.
5.3 Things to note
-
Non-string keys:
If the dictionary's key is not a string type, a TypeError will be thrown by default. Can be set byskipkeys=True
Skip these keys. -
Special values:
By default, special values such as NaN and Infinity can be serialized. If not required, you can set itallow_nan=False。
-
Coding issues:
ifensure_ascii=True
(default),All non-ASCII characters will be escaped into \uXXXX format.
If you want to retain the original characters, you can set itensure_ascii=False。
-
Performance issues:
For very large data, () will load the entire object into memory. If memory is limited, consider using streaming tools.
5.4 Example
5.4.1 Basic usage
import json # Python Dictionarydata = { "name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"] } # Serialize to JSON stringjson_str = (data,ensure_ascii=False) print(json_str) # {"name": "Chen Nan", "age": 10028.26, "skill": ["Encouraging Demon Sutra", "Taishang Forgetful Love Record", "Tongtian and Earth Magical Art"]}
5.4.2 Custom serialization
If a Python object contains a type that cannot be serialized directly (such as datetime), you can usedefault
The parameter specifies a processing function:
import json from datetime import datetime def custom_serializer(obj): """ Custom serialization functions :param obj: :return: """ if isinstance(obj, datetime): return ('%Y-%m-%d %H:%M:%S') # Convert datetime to string raise TypeError("Type not serializable") # Python dictionary containing datetime objectdata = { "name": "Chen Nan", "age": 10028.26, "skill": ["Demon Calling Sutra", "The Record of Forgetful Love", "Tiantian and Earth Magical Art"], "created": () } # Serialize to JSON string, indent: beautify, ensure_ascii: output Chinese, sort_keys: sortjson_str = (data, default=custom_serializer, indent=4, ensure_ascii=False, sort_keys=True) print(json_str)
Summarize
This is the article about Python JSON module loads, load, dump, and dumps functions. For more related Python JSON module loads, load, dump, and dumps content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!