简体   繁体   English

不打算使用json.load将json在Python中反序列化为字符串

[英]Not about to deserialize json kept as string in Python using json.load

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

I'm using this to concatenate json data from various api calls, into a string. 我正在使用它将来自各种api调用的json数据连接成一个字符串。

Now, when I want to read the data/load the variable "strdata" into a json format, using 现在,当我想读取数据/将变量“strdata”加载到json格式时,使用

json.loads(strdata)

but it doesn't work. 但它不起作用。 I presume that considering that I'm concatenating a serialized string with another, I should dump the entire strdata first and then load it again. 我认为考虑到我将序列化字符串与另一个串联,我应该首先转储整个strdata,然后再次加载它。 But that doesn't work either. 但这也不起作用。

Initialize strdata as a list: strdata初始化为列表:

strdata = []

Inside the loop, append the JSON dumps to the list: 在循环内部,将JSON转储附加到列表:

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

To store the list in a file: 要将列表存储在文件中:

json.dump(strdata, f)

To load the list from the file: 要从文件加载列表:

strdata = json.load(f)

To retrieve the original data (or the data.__dict__ proxy), call json.loads on each item in strdata : 要检索原始数据(或data.__dict__代理),请在strdata中的每个项目上调用strdata

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

JSON has a well-defined format . JSON具有明确定义的格式 You can not create valid JSON (such as a list of elements) by simply concatenating two JSON strings. 您不能通过简单地连接两个JSON字符串来创建有效的JSON(例如元素列表)。


There is a more sophisticated way to handle this problem: use a custom encoder ( cls=CustomEncoder ), and a custom decoder ( object_hook=custom_decoder ): 有一种更复杂的方法来处理这个问题:使用自定义编码器( 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}}]]

The advantage of doing it this way is that it requires only one call to json.dump to store the data, and only one call to json.load to retrieve the data. 这样做的好处是它只需要一次调用json.dump来存储数据,只需要调用json.load来检索数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM