JSON processing in Python: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 6: | Line 6: | ||
=Overview= | =Overview= | ||
=Serialization= | |||
<syntaxhighlight lang='python'> | |||
import json | |||
data = ... | |||
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 15: | Line 25: | ||
print(data["details"]["shape"]["texture"]) # displays bumpy | print(data["details"]["shape"]["texture"]) # displays bumpy | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Safely Navigate a Complex Data Structure= | =Safely Navigate a Complex Data Structure= | ||
Suggestions on how to safely recursively 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}} | {{Internal|Python Safely Navigate a Complex Data Structure#Overview|Safely Navigate a Complex Data Structure}} |
Revision as of 01:07, 9 March 2022
External
Internal
Overview
Serialization
import json
data = ...
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
Suggestions on how to safely recursively navigate a complex data structure: