解析包含“对象”的JSON

时间:2014-01-18 05:55:55

标签: python json

我从应用程序获取数据,该应用程序返回似乎是JSON的内容,但带有一些“对象”。例如:

{"rgEvtData":[new VisData(0,0,1,0,1,0,0,0,0,-1),new VisData(0,1,1,1,1,0,0,0,0,-1),new VisData(0,2,1,2,1,0,0,0,0,-1),new VisData(0,3,2,0,1,0,0,0,0,-1),new VisData(0,4,2,1,1,0,0,0,0,-1),new VisData(0,5,2,2,1,0,0,0,0,-1),new VisData(0,6,2,3,1,0,0,0,0,-1),new VisData(0,7,3,0,1,0,0,0,0,-1),new VisData(0,8,3,1,1,0,0,0,0,-1)]}

任何想法我是否可以在没有肮脏的变通方法(即replace()或regexp)的python上解析它?

1 个答案:

答案 0 :(得分:1)

不,你不能。
即使python可以解析它,它会对VisData s做什么?

我认为您唯一的选择(除了提到的方法),将此字符串转换为有效的JSON。例如,如果您有多个类名,请将new VisData(...)替换为[...]{"class": "VisData", "args": [...]}。但你说你不想那样。

<强>更新
我有一个例子,我认为这是你需要的 它以您提供的格式处理自定义类。 它还可以处理多个类和任何数量/类型的构造函数参数。

import re
import json

# our python VisData class
class VisData(object):
    def __init__(self, *args):
        self.args = args

# object hook to convert our {"class":"VisData","args":[...]} dict to VisData insances
def object_hook(obj):
    # if we recognize our object describer dict
    if len(obj) == 2 and "class" in obj and "args" in obj:
        # instantiate our classes by name
        clazz = globals()[obj["class"]]
        args = obj["args"]
        return clazz(*args)
    return obj

# input
input_string = '{"rgEvtData":[new VisData(0,0,1,0,1,0,0,0,0,-1),new VisData(0,1,1,1,1,0,0,0,0,-1)]}'

# make it json
json_string = re.sub(r'new (\w+)\(([^\)]*)\)', r'{"class":"\1","args":[\2]}', input_string)

# parse it with our object hook
data = json.loads(json_string, object_hook=object_hook)

# result
print(data)                         # -> {u'rgEvtData': [<__main__.VisData object at 0x1065d8210>, <__main__.VisData object at 0x1065d8250>]}
print(data["rgEvtData"][0])         # -> <__main__.VisData object at 0x1065d8210>
print(data["rgEvtData"][0].args)    # -> (0, 0, 1, 0, 1, 0, 0, 0, 0, -1)