Skip to content

Python object serialization

lanzhiwang edited this page Sep 30, 2019 · 7 revisions

JSON

import json
<str>    = json.dumps(<object>, ensure_ascii=True, indent=None)
<object> = json.loads(<str>)

To preserve order:

from collections import OrderedDict
<object> = json.loads(<str>, object_pairs_hook=OrderedDict)

Read File

def read_json_file(filename):
    with open(filename, encoding='utf-8') as file:
        return json.load(file)

Write to File

def write_to_json_file(filename, an_object):
    with open(filename, 'w', encoding='utf-8') as file:
        json.dump(an_object, file, ensure_ascii=False, indent=2)

Pickle

import pickle
<bytes>  = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)

Read Object from File

def read_pickle_file(filename):
    with open(filename, 'rb') as file:
        return pickle.load(file)

Write Object to File

def write_to_pickle_file(filename, an_object):
    with open(filename, 'wb') as file:
        pickle.dump(an_object, file)

marshal

shelve

Clone this wiki locally