JSON processing in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 42: Line 42:
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
import json
import json
import Path from pathlib
from pathlib import Path


d = json.load(Path('somefile.json'))
d = json.load(Path('somefile.json'))

Revision as of 02:49, 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
from pathlib import Path

d = json.load(Path('somefile.json'))

Safely Navigate a Complex Data Structure

Suggestions on how to safely recursively navigate a complex data structure:

Safely Navigate a Complex Data Structure