Python tutorial: json Python3 built-in modules of the encoding and decoding method Summary
Outline
Python3 we use encoding and decoding module incorporating json JSON objects, JSON (JavaScript Object Notation) is designated RFC 7159 (abandoned RFC 4627) and ECMA-404 is a lightweight data-interchange format, text inspired by JavaScript object syntax (although it is not a strict subset of JavaScript 1). The following is a Python objects -> JSON an object control table.
dumps coding
We use Python object dumps will be encoded as a JSON object, of course, dumps only finished sequence into str, and dump must pass the file descriptor, save the serialized str to file, their function is defined as
dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
dump(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)
Coding dictionary
import json
D = {'one': 1, 'two': 2, 'three': 3}
J = json.dumps(D)
print(J)
Sample results:
{"one": 1, "two": 2, "three": 3}
Codelists
import json
L = [1, 'Python ', {'one': 1, 'two': 2, 'three': 3}, '']
J = json.dumps(L)
print(J)
Sample results:
[1, "Python ", {"one": 1, "two": 2, "three": 3}, ""]
coding
import json
S = 'Python'
J = json.dumps(S)
print(J)
Sample results:
"Python"
JSON formatted output
import json
L = [1, 'Python ', {'one': 1, 'two': 2, 'three': 3}, True]
J = json.dumps(L, sort_keys=True, indent=4)
print(J)
Sample results:
[
1,
"Python ",
{
"one": 1,
"three": 3,
"two": 2
},
true
]
loads decoding
We use loads to decode JSON objects. Python decoding result i.e. the corresponding object type. Of course, loads only completed deserialization, load receiving only the file descriptor, and to complete the read file deserialization. Their function is defined as
loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
For example, we used to decode the data of the previous example
import json
jsondata = '''
[
1,
"Python ",
{
"one": 1,
"three": 3,
"two": 2
},
true
]
'''
J = json.loads(jsondata)
print(type(J))
print(J)
Sample results:
<class 'list'>
[1, 'Python ', {'one': 1, 'three': 3, 'two': 2}, True]
We can see that the success of the previous example JSON object is decoded, and the final result of decoding Python list object type, in line with the results of the Python object -JSON table of objects.
Today on json encoding and decoding methods begin with summary so much more Python tutorials will continue to update!