【问题标题】:Convert complex string to json in python在python中将复杂字符串转换为json
【发布时间】:2020-11-25 18:35:57
【问题描述】:

我有一个包含复杂 json 的字符串。我需要转成json格式

输入:

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

输出:

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

【问题讨论】:

  • 你尝试了什么

标签: python json string


【解决方案1】:

使用 split 方法来分隔字符串。

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]

输出:

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

【讨论】:

    【解决方案2】:
    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_)
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多