python将json字典转换为对象格式

示例代码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_data.name)   #  此时会报错

运行效果:

示例代码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_data.name)   

运行效果:

示例代码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_data.name)
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(obj.name)
print("*" * 100)
print(obj.location)
print("*" * 100)
print(obj.location.city)
print("*" * 100)
print(obj.location.city1)

运行结果:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值