python中msg是什么意思_用Python解析JSON MSG

I am trying to parse a json MSG into a python dict.

For reference, the message is received from the Things Network with the python MQTT handler.

Here is the format I am receiving when I print the object

msg = MSG(variable_group=MSG(data0=0, data1=0, data2=0), variable2='name', variable3='num')

In its default state, I can access individual fields by msg.variable2 for example which provides 'name' but does not provide the variable name itself.

This is fine for a scenario in which I hardcode everything into my system, but I would like it to be a bit more adaptable and create new entries for variables as they come in.

Is there any way to parse this in such a way that I get both the data and the variable name?

Thanks!

EDIT:

From the input above, I would like to get a python dict containing the variable name and data.

dict =

{

variable_group : MSG(data0=0, data1=0, data2=0),

variable2 : 'name',

variable3 : 'num'

}

Currently, I can access the data via a for loop and can print the variable names if I print the entire structure, but cannot access the variable names through a looping mechanism

EDIT 2:

After doing some digging on the wrapper found the following:

def _json_object_hook(d):

return namedtuple("MSG", d.keys())(*d.values())

def json2obj(data):

return json.loads(data, object_hook=_json_object_hook)

Where the input shown above is created by passing it as 'data' to json2obj.

I am still unsure how to get a dict out of this format, haven't used object_hooks before.

解决方案

From discussion in the comments below, it appears that the MSG object is a namedtuple created on the fly out of the json object.

In a case like that you can get the fields by looking at the _fields of the object. You can dict-ify a namedtuple like this

def nt_to_dict(nt):

return {field, getattr(nt, field) for field in nt._fields}

or you could just inspect the object by trolling _fields in code and using getattr as needed

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值