Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string with multiple dictionaries, so json.load can parse it? [closed]

How can I write a function in python that that will take a string with multiple dictionaries, one per line, and convert it so that json.loads can parse the entire string in single execution.

For example, if the input is (one dictionary per line):

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

This will not parse with json.loads(Input). I need to write a function to modify it so that it does parse properly. I am thinking if the function could change it to something like this, json will be able to parse it, but am not sure how to implement this.:

Input2 = """{ "Dict1" : {"a":[1,2,3], "b":[4,5]},
               "Dict2" : {"z":[-1,-2], "x":-3} }"""
like image 673
nasia jaffri Avatar asked Sep 11 '25 05:09

nasia jaffri


1 Answers

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

Not in function form like you requested, but the code would be almost the same. Also, this produces the dicts in a list.

Adding the following might be of use to you

>>> 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]}}
like image 161
Totem Avatar answered Sep 13 '25 18:09

Totem