1
strdata = strdata + json.dumps(data, default=lambda o: o.__dict__)

我正在使用它将来自各种 api 调用的 json 数据连接成一个字符串。

现在,当我想读取数据/将变量“strdata”加载为 json 格式时,使用

json.loads(strdata)

但它不起作用。我认为考虑到我正在将一个序列化字符串与另一个字符串连接,我应该首先转储整个 strdata,然后再次加载它。但这也行不通。

4

1 回答 1

4

初始化strdata为列表:

strdata = []

在循环内部,将 JSON 转储附加到列表中:

strdata.append(json.dumps(data, default=lambda o: o.__dict__))

要将列表存储在文件中:

json.dump(strdata, f)

要从文件加载列表:

strdata = json.load(f)

要检索原始数据(或data.__dict__代理),请对 json.loads 中的每个项目调用strdata

[json.loads(item) for item in strdata]

JSON 具有明确定义的格式。您无法通过简单地连接两个 JSON 字符串来创建有效的 JSON(例如元素列表)。


有一种更复杂的方法来处理这个问题:使用自定义编码器 ( cls=CustomEncoder) 和自定义解码器 ( object_hook=custom_decoder):

import json

class Foo(object):
    def __init__(self, x=1, y='bar'):
        self.x = x
        self.y = y

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Foo):
            return obj.__dict__
        else:
            return json.JSONEncoder.default(self, obj)

filename = '/tmp/test.json'
with open(filename, 'w') as f:
    json.dump(
        [Foo(1, 'manchego'), Foo(2, 'stilton'), [{'brie': Foo(3,'gruyere')}]],
        f, cls=CustomEncoder)

def custom_decoder(dct):
    try:
        return Foo(**dct)
    except TypeError:
        return dct

with open(filename, 'r') as f:
    newfoo = json.load(f, object_hook=custom_decoder)
print(newfoo)
# [{"y": "manchego", "x": 1}, {"y": "stilton", "x": 2}, [{"brie": {"y": "gruyere", "x": 3}}]]

这样做的好处是它只需要一次调用来json.dump存储数据,并且只需要一次调用json.load来检索数据。

于 2013-05-26T15:55:13.473 回答