Differences between revisions 3 and 4
Revision 3 as of 2023-04-11 01:06:02
Size: 398
Comment:
Revision 4 as of 2023-04-11 01:21:55
Size: 1766
Comment:
Deletions are marked like this. Additions are marked like this.
Line 14: Line 14:
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
Line 22: Line 25:
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` ||

----
Line 26: Line 43:
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)
}}}

----



Line 27: Line 64:

Serialize an object into a JSON-encoded string.

All dictionary keys are coerced into strings for this serialization. This may break roundtrip conversions.

----

Line 30: Line 75:
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.

----


Line 32: Line 90:
--- Deserialize a JSON-encoded string into an object.

The string can be any of `str`, `byte`,` or `bytearray` types, as long as it is UTF-{8,16,32} encoded.

----

Python Json

json is a module that supports encoding and decoding 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 string into an object.

The string 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


CategoryRicottone

Python/Json (last edited 2023-06-15 18:40:42 by DominicRicottone)