<jupyter_start><jupyter_text>Table of Content- [6.2 Reading and Writing JSON Data](6.2) ---  6.2 Reading and Writing JSON Data Discussion Object Hook- OrdererDict<jupyter_code>import json
from collections import OrderedDict

s = '{"first_name": "Wei", "last_name": "Lee", "age": 22}'
data = json.loads(s, object_pairs_hook=OrderedDict)
data<jupyter_output><empty_output><jupyter_text>- Instance<jupyter_code>class JSONObject:
    def __init__(self, d):
        self.__dict__ = d
        
data = json.loads(s, object_hook=JSONObject)
print(data.first_name, data.last_name, data.age)<jupyter_output>Wei Lee 22<jupyter_text>Serialization and DeserializationNormally, instance are not serializable<jupyter_code>class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
p = Point(2, 3)
json.dumps(p)
def serialize_instance(obj):
    d = {'__classname__': type(obj).__name__}
    d.update(vars(obj))
    return d
classes = {
    'Point': Point
    
}
def deserialize_object(d):
    clsname = d.pop('__classname__', None)
    if clsname:
        cls = classes[clsname]
        obj = cls.__new__(cls)
        for key, value in d.items():
            setattr(obj, key, value)
        return obj
    else:
        return d
p = Point(2, 3)
s = json.dumps(p, default=serialize_instance)
print(s)
a = json.loads(s, object_hook=deserialize_object)
print(a)
print(a.x, a.y)<jupyter_output>{"y": 3, "x": 2, "__classname__": "Point"}
<__main__.Point object at 0x104b3f8d0>
2 3
{'fraction_non_alphanumeric': 0.12944332662642521, 'fraction_numerical': 0.01676727028839705, 'mean_word_length': 3.797427652733119, 'pattern_counts': {'":': 6, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '443025', 'license': 'MIT', 'n_tokens_mistral': 557, 'n_tokens_neox': 548, 'n_words': 128, 'path': 'Ch06 - Data Encoding and Processing.ipynb', 'repo_name': 'Lee-W/Python_Cookbook', 'size': '1491'}