用Python解析JSON MSG [英] Parse JSON MSG in Python

查看:177
本文介绍了用Python解析JSON MSG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将json MSG解析为python dict.

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

作为参考,使用Python MQTT处理程序从物联网接收消息.

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')

在默认状态下,我可以通过msg.variable2访问单个字段,例如,该字段提供名称",但不提供变量名称本身.

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?

谢谢!

从上面的输入中,我想获取一个包含变量名称和数据的python字典.

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'
}

当前,我可以通过for循环访问数据,并且可以在打印整个结构时打印变量名,但不能通过循环机制访问变量名

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

在包装器上进行了一些挖掘之后,发现以下内容:

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)

上面显示的输入是通过将其作为数据"传递到json2obj来创建的.

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

我仍然不确定如何使用这种格式的字典,以前没有使用过object_hooks.

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

推荐答案

从下面的注释中的讨论中可以看出,MSG对象似乎是在json对象外快速创建的namedtuple.

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

在这种情况下,您可以通过查看对象的_fields来获取字段.您可以像这样指定一个命名元组

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}

或者您可以通过在代码中拖曳_fields并根据需要使用getattr来检查对象

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

这篇关于用Python解析JSON MSG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆