简体   繁体   中英

Convert complex string to json in python

I have string containing complex json. I need to convert it into json format

Input:

"aa = 2, bb = [{"hh":"dd"},{"hh":"dd"}], cc = 2020-07-08,10AM"

OutPut:

{ "aa": 2, "bb": [{"hh":"dd"},{"hh":"dd"}], "cc": "2020-07-08,10AM" }

Use the split method to separate the string.

input_ = "aa = 2, bb = [{'hh':'dd'},{'hh':'dd'}], cc = 2020-07-08 ,10AM"

a = input_.split(', ')

output = {}
for i in range(len(a)):
    b = a[i].split("=")
    output[b[0]] = b[1]

Output:

{'aa ': ' 2', 'bb ': " [{'hh':'dd'},{'hh':'dd'}]", 'cc ': ' 2020-07-08 ,10AM'}
input_string='aa = 2, bb = [{"hh":"dd"},{"hh":"dd"}], cc = 2020-07-08 ,10AM'


ll=input_string.split(',')
parsed=[]
for i in range(len(ll)):
    if '=' not in ll[i]:
        latest_index_with_equal=i
        while True:
            if latest_index_with_equal>=0:
                if '=' in ll[latest_index_with_equal-1]:
                    break
                else:
                    latest_index_with_equal-=1
            else:
                break
        parsed.append(ll[latest_index_with_equal-1]+ll[i])
    else:
        if '=' in ll[i+1]:
            parsed.append(ll[i])
parsed_=[]
for i in range(len(parsed)):
    parsed[i]=parsed[i].replace('}{','},{')
    if ('{' not in parsed[i] or '[' not in parsed[i]) or (parsed[i].split('=')[-1].replace(' ','')[0] == '[' and parsed[i].split('=')[-1].replace(' ','')[-1] == ']' or parsed[i].split('=')[-1].replace(' ','')[0] == '{' and parsed[i].split('=')[-1].replace(' ','')[-1] == '}'):
        if parsed[i][0]==' ':
            parsed[i]=parsed[i][1:]
        parsed_.append(parsed[i])
out_={}
for i in parsed_:
    key=i.split('=')[0]
    if key[-1]==' ':
        key=key[:-1]
    value=i.split('=')[-1]
    if value[-1]==' ':
        value=value[:-1]
    if value[0]==' ':
        value=value[1:]
    
    if (value[0] == '[' and value[-1] == ']') or (value[0] == '{' and value[-1] == '}'):
        value=eval(value)
    elif value.isdigit():
        value=int(value)
    else:
        value=str(value)
    out_[key]=value
print(out_)

Output:

{'aa': 2, 'bb': [{'hh': 'dd'}, {'hh': 'dd'}], 'cc': '2020-07-08 10AM'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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