python split string json into multiple variables and create dataframes

243 Views Asked by At

Below is my string in python3

Please assume below string is in a loop

On First loop I get below string string as input

string='{a:1,b:1}{a:2,b:2}{a:3,b:4}'

On Second loop I get below string as input

string='{a:1,b:6}{a:2,b:6}'

On each loop pandas dataframe should created as below:

First loop

a b
1 1
2 2
3 4

second loop

a b
1 6
2 6

Can anyone help with this I am struggling to crack this logic

1

There are 1 best solutions below

1
On

You can split the input data by regex, then parse the output as json object

>>> import re
>>> string='{a:1,b:1}{a:2,b:2}{a:3,b:4}'
>>> r = '({a:\d+,b:\d+})'
>>> out = [item for item in re.split(r, string) if item !='']
>>> out
['{a:1,b:1}', '{a:2,b:2}', '{a:3,b:4}']

Update

Use this regex pattern for matching any character:

r = '({a:.*?[^,],b:.*?[^}]})'

Result:

>>> import re
>>> string='{a:1ac,b:1_e}{a:2zz,b:222}{a:33,b:44}'
>>> r = '({a:.*?[^,],b:.*?[^}]})'
>>> out = [item for item in re.split(r, string) if item !='']
>>> out
['{a:1ac,b:1_e}', '{a:2zz,b:222}', '{a:33,b:44}']