티스토리 뷰

Standard Library

JSON

nickas 2019. 7. 2. 14:09
import json

data = {
	'name': 'ACME',
    'shares': 100,
    'price': 542.23
}

json_str = json.dumps(data)

data = json.loads(json_str)

# Writing JSON data
with open('data.json', 'w') as f:
	json.dump(data, f)
    
# Reading data back
with open('data.json', 'r') as f:
	data = json.load(f)
    
json.dumps(False) # 'false'

d = {'a': True,
     'b': 'Hello',
     'c': None}
     
json.dumps(d)
# '{"b": "Hello", "C": null, "a": true}'

s = '{"name": "ACME", "shares": 50, "price": 490.1}'
from collections import OrderedDict
data = json.loads(s, object_pairs_hook=OrderedDict)


class JSONObject:
	def __init__(self, d):
    	self.__dict__ = d
        
data = json.loads(s, object_hook=JSONObject)
data.name
data.shares
data.price

print(json.dumps(data))
# {"price": 542.23, "name": "ACME", "shares": 100}

print(json.dumps(data, indent=4))
"""
{
    "price": 542.23,
    "name": "ACME",
    "shares": 100
}
"""

print(json.dumps(data, sort_keys=True)
# {"name": "ACME", "price": 542.23, "shares": 100}
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def serialize_instance(obj):
	d = { '__classname__' : type(obj).__name__ }
    d.update(vars(obj))
    
    return d
    
classes = {
	'Point': Point
}

def unserialize_object(d):
	clsname = d.pop('__classname__', None)
    if claname:
    	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)
s
# '{"__classname__": "Point", "y": 3, "x": 2}'
a = json.loads(s, object_hook=unserialize_object)
a
# <__main__.Point object at 0x1017577d0>
a.x
# 2
a.y
# 3

JSON Documents

 

json — JSON encoder and decoder — Python 3.7.4rc1 documentation

json — JSON encoder and decoder Source code: Lib/json/__init__.py JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (al

docs.python.org

 

'Standard Library' 카테고리의 다른 글

copy(), deepcopy()  (0) 2019.07.05
dis  (0) 2019.07.05
최근에 올라온 글
글 보관함