如何重写JSONDecoder以不同方式处理某些字符串匹配

时间:2019-02-21 01:07:34

标签: python json dictionary

我想更改json文件中的某些值(嵌套字典和数组)。我认为方便的方法是利用JSONDecoder。

但是,它没有按我期望的那样工作。我已经使用了完全相同的方法来使JSONEncoder将np.arrays转换为列表,从而不会破坏编码器。

在没有让它做我想要的事情之后,我想也许可以尝试解码器。同样的问题,它似乎从未调用default来处理字符串。也许在处理字符串时,甚至在处理其他类型的对象时,都不会调用default吗?

# key, val are arguments passed in, e.g. ("bar", "2.0rc1")
# Replace the value "2.0rc1" everywhere the "bar" key is found

class StringReplaceDecoder(json.JSONDecoder):
    def default(self, obj):
        if isinstance(obj, str):
            print("Handling obj str: {}".format(obj))
            if obj == key:
                return val
        return json.JSONEncoder.default(self, obj)


json_dump = json.dumps(dict)
json_load = json.loads(json_dump, cls=StringReplaceDecoder)

# Example input
{a:{foo:"", bar:"1.3"}, b:{d:{foo:""}, z:{bar:"1.5"}}}
# Example desired output:
{a:{foo:"", bar:"2.0rc1"}, b:{d:{foo:""}, z:{bar:"2.0rc1"}}}

1 个答案:

答案 0 :(得分:0)

找到可行的解决方案后,我发现了一个远远优于以前的Google搜索的衬里。

我的问题的正确答案是from nested_lookup import nested_update

对于它的价值,我还发现object_hook也完全符合我的要求:

def val_hook(obj):
    return_d = {}
    if isinstance(obj, dict):
        for k in obj:
            if in_key == k:
                return_d[k] = in_val
            else:
                return_d[k] = obj[k]
        return return_d
    else:
        return obj

json_dump = json.dumps(in_dict)
json_load = json.loads(json_dump, object_hook=val_hook)

参考