如何使用多个字典转换字符串,以便 json.load 可以解析它?

nas*_*fri 4 python json dictionary

我如何在 python 中编写一个函数,该函数将接受一个带有多个字典的字符串,每行一个,并将其转换,以便 json.loads 可以在单次执行中解析整个字符串。

例如,如果输入是(每行一个字典):

Input = """{"a":[1,2,3], "b":[4,5]}
           {"z":[-1,-2], "x":-3}"""
Run Code Online (Sandbox Code Playgroud)

这不会用 json.loads(Input) 进行解析。我需要编写一个函数来修改它,以便它能够正确解析。我在想如果该函数可以将其更改为这样的内容,json将能够解析它,但我不确定如何实现它:

Input2 = """{ "Dict1" : {"a":[1,2,3], "b":[4,5]},
               "Dict2" : {"z":[-1,-2], "x":-3} }"""
Run Code Online (Sandbox Code Playgroud)

Tot*_*tem 6

>>> import json  
>>>
>>> dict_str = """{"a":[1,2,3], "b":[4,5]}
>>>               {"z":[-1,-2], "x":-3}"""
>>>
>>> #strip the whitespace away while making list from the lines in dict_str 
>>> dict_list = [d.strip() for d in dict_str.splitlines()]
>>>                                                        
>>> dict_list
>>> ['{"a":[1,2,3], "b":[4,5]}', '{"z":[-1,-2], "x":-3}']
>>>
>>> j = [json.loads(i) for i in dict_list]
>>> j
>>> [{u'a': [1, 2, 3], u'b': [4, 5]}, {u'x': -3, u'z': [-1, -2]}]
Run Code Online (Sandbox Code Playgroud)

不是像您要求的那样采用函数形式,但代码几乎相同。另外,这会生成列表中的字典。

添加以下内容可能对您有用

>>> d = {('Dict'+str(i+1)):v for i in range(len(j)) for v in j}
>>> d
>>> {'Dict1': {u'x': -3, u'z': [-1, -2]}, 'Dict2': {u'x': -3, u'z': [-1, -2]}}
Run Code Online (Sandbox Code Playgroud)