JSON processing in Python: Difference between revisions
Jump to navigation
Jump to search
(11 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=External= | =External= | ||
* https://realpython.com/python-json/ | |||
=Internal= | |||
* [[Python Code Examples#Code_Examples|Python Code Examples]] | |||
* [[Python Module json]] | * [[Python Module json]] | ||
=Overview= | =Overview= | ||
=Serialization= | |||
Serialization into a string: | |||
<syntaxhighlight lang='python'> | |||
import json | |||
d = ... # data structure | |||
s = json.dumps(d, indent=4, sort_keys=True) | |||
</syntaxhighlight> | |||
There are situations when instances in the data structure are not serializable: | |||
<font size=-1> | |||
TypeError: Object of type datetime is not JSON serializable | |||
</font> | |||
In this case, use: | |||
<syntaxhighlight lang='python'> | |||
s = json.dumps(d, indent=4, sort_keys=True, default=str) | |||
</syntaxhighlight> | |||
Serialization into a file: | |||
<syntaxhighlight lang='python'> | |||
with open("data_file.json", "w") as f: | |||
json.dump(data, f) | |||
</syntaxhighlight> | |||
=Deserialization= | |||
<syntaxhighlight lang='python'> | <syntaxhighlight lang='python'> | ||
import json | import json | ||
Line 13: | Line 38: | ||
print(data["details"]["shape"]["texture"]) # displays bumpy | print(data["details"]["shape"]["texture"]) # displays bumpy | ||
</syntaxhighlight> | </syntaxhighlight> | ||
From file: | |||
<syntaxhighlight lang='python'> | |||
import json | |||
filename = 'somefile.json' | |||
with open(filename, 'rt') as f: | |||
ds = json.load(f) | |||
</syntaxhighlight> | |||
=Safely Navigate a Complex Data Structure= | |||
Suggestions on how to safely recursively navigate a complex data structure: | |||
{{Internal|Python Safely Navigate a Complex Data Structure#Overview|Safely Navigate a Complex Data Structure}} |
Latest revision as of 02:55, 13 March 2022
External
Internal
Overview
Serialization
Serialization into a string:
import json
d = ... # data structure
s = json.dumps(d, indent=4, sort_keys=True)
There are situations when instances in the data structure are not serializable:
TypeError: Object of type datetime is not JSON serializable
In this case, use:
s = json.dumps(d, indent=4, sort_keys=True, default=str)
Serialization into a file:
with open("data_file.json", "w") as f:
json.dump(data, f)
Deserialization
import json
data = json.loads('{"color":"blue", "size":10, "details":{"shape":{"texture":"bumpy", "orientation":"vertical"}}}')
print(data.get("color")) # displays blue
print(data["color"]) # displays blue
print(data.get("size")) # displays 10
print(data["details"]["shape"]["texture"]) # displays bumpy
From file:
import json
filename = 'somefile.json'
with open(filename, 'rt') as f:
ds = json.load(f)
Suggestions on how to safely recursively navigate a complex data structure: