示例代码1:
from collections import OrderedDict
import json
data = '{"name":"张三","age":50,"prices":520.1314}'
json_data = json.loads(data, object_pairs_hook=OrderedDict)
print(json_data)
print(json_data['name'])
# print(json_) # 此时会报错
运行效果2:
示例代码2:
from collections import OrderedDict
import json
class JsonObject(object):
def __init__(self, d):
self.__dict__ = d
data = '{"name":"张三","age":50,"prices":520.1314}'
json_data = json.loads(data, object_hook=JsonObject)
print(json_data)
# print(json_data['name']) # 此时会报错
print(json_)
运行效果:
示例代码3:
import json
class JsonObject(object):
def __init__(self, d):
self.__dict__ = d
data = '{"name":"张三","age":50,"prices":520.1314,"books":{"语文":"济南的冬天","数学":"奥数题"}}'
json_data = json.loads(data, object_hook=JsonObject)
print(json_data)
# print(json_data['name']) # 此时会报错
print(json_)
print(json_data.books)
print(json_data.books.语文)
运行效果:
示例代码4:
class DictObj(dict):
def __getattr__(self, item):
print("get attr")
if item not in self:
return None
else:
value = self[item]
if isinstance(value, dict):
value = DictObj(value)
return value
dic = {
"name": "dgw",
"location": {
"province": "山东省",
"city": "青岛市"
}
}
obj = DictObj(dic)
print()
print("*" * 100)
print(obj.location)
print("*" * 100)
print(obj.location.city)
print("*" * 100)
print(obj.location.city1)
运行结果: