|
Size: 1766
Comment:
|
← Revision 7 as of 2023-06-15 18:40:42 ⇥
Size: 1843
Comment:
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 3: | Line 3: |
| '''`json`''' is a module that supports encoding and decoding JSON files. | '''`json`''' is a module that supports (de-)serializing JSON files. |
| Line 90: | Line 90: |
| Deserialize a JSON-encoded string into an object. | Deserialize a JSON-encoded `str`-like object. |
| Line 92: | Line 92: |
| The string can be any of `str`, `byte`,` or `bytearray` types, as long as it is UTF-{8,16,32} encoded. | The `str`-like object can be any of `str`, `byte`, or `bytearray` types, as long as it is UTF-{8,16,32} encoded. |
| Line 102: | Line 102: |
| [[https://pymotw.com/3/json/|Python Module of the Day article for json]] |
Python Json
json is a module that supports (de-)serializing JSON files.
Example
some_object = {"a": "a", "b": [1, 2.1]}
some_string = json.dumps(some_object) # '{"a": "a", "b": [1, 2.1]}'
assert some_object == json.loads(some_string) # True
Usage
JSON and Python objects are translated as:
JSON |
Python |
object |
dict |
array |
list |
string |
str |
number (int) |
int |
number (real) |
float |
true |
True |
false |
False |
null |
None |
Dump
Serialize an object and write it to a file.
with open('example.json', 'w') as f:
json.dump(['example'], f)Can also be used with a filestream object.
from io import StringIO io = StringIO() json.dump(['example'], io)
DumpS
Serialize an object into a JSON-encoded string.
All dictionary keys are coerced into strings for this serialization. This may break roundtrip conversions.
Load
Deserialize a JSON-encoded file.
with open('example.json', 'r') as f:
some_object = json.load(f)If the file is opened as a binary file (i.e. 'rb' instead of 'r'), it should be UTF-{8,16,32} encoded.
LoadS
Deserialize a JSON-encoded str-like object.
The str-like object can be any of str, byte, or bytearray types, as long as it is UTF-{8,16,32} encoded.
See also
Python json module documentation
Python Module of the Day article for json
