JSON(JavaScript Object Notation)
python中内置库为json。
In [399]: d = dict(name='Tom', age=20, sex='male', tall=185)
In [400]: d
Out[400]: {'age': 20, 'name': 'Tom', 'sex': 'male', 'tall': 185}
In [401]: import json
In [402]: json.dumps(d)
Out[402]: '{"name": "Tom", "age": 20, "sex": "male", "tall": 185}'
In [403]: jd = json.dumps(d)
In [404]: from collections import OrderedDict
In [405]: data = json.loads(jd, object_hook=OrderedDict)
In [406]: data
Out[406]: OrderedDict([('name', 'Tom'), ('age', 20), ('sex', 'male'), ('tall', 185)])
#该处的使用还没搞懂,写这个博客就是为了记录这个。
In [407]: class JSONObject:
...: def __init__(self, d):
...: self.__dict__ = d
...:
In [408]: data = json.loads(jd, object_hook=JSONObject)
In [409]: data.__dict__
Out[409]: {'age': 20, 'name': 'Tom', 'sex': 'male', 'tall': 185}
In [410]: data.age
Out[410]: 20
In [411]: data.name
Out[411]: 'Tom'
In [412]: data.sex
Out[412]: 'male'
参考: python cookbook