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

时间:2013-11-17 23:31:51

标签: python json dictionary

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

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

Input = """{"a":[1,2,3], "b":[4,5]}
           {"z":[-1,-2], "x":-3}"""

这不会用json.loads(输入)解析。我需要编写一个函数来修改它,以便它可以正确解析。 我在想如果函数可以将它改成这样的东西,json将能够解析它,但我不确定如何实现它。:

Input2 = """{ "Dict1" : {"a":[1,2,3], "b":[4,5]},
               "Dict2" : {"z":[-1,-2], "x":-3} }"""

1 个答案:

答案 0 :(得分:3)

>>> 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]}]

不是您所要求的功能形式,但代码几乎相同。此外,这会在列表中生成dicts。

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

>>> 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]}}
相关问题