【问题标题】:Encode to JSON from unstructured string从非结构化字符串编码为 JSON
【发布时间】:2014-05-01 11:57:56
【问题描述】:

我有一个如下所示的字符串:

{"name": "john", "smith", "paul", "address": "nyc", "chicago", "age": 50, 60}

我必须将其转换为 JSON,如下所示:

{"name": ["john", "smith", "paul"], "address": ["nyc", "chicago"], "age": [50, 60]}

有什么办法吗?

【问题讨论】:

  • 是什么产生了字符串?你能让 it 生成有效的 JSON 吗?
  • 你有什么困难?您需要指导如何开始吗?根据您的需要,您可以使用正则表达式或解析器生成器(例如 pyparsing)将字符串解析为字典,或者(更糟糕的是)只需插入括号以使其成为有效的 json

标签: python json python-2.7


【解决方案1】:
str_temp = '{"name": "john", "smith", "paul", "address": "nyc", "chicago", "age": 50, 60}'
index_temp = str_temp.split(',')
temp_flag = 0
temp_list = []
for object in index_temp:
    if object.find(':') != -1:
        if temp_flag == 0:
            temp_count = object.find(':')
            object = object[:temp_count + 1] + '[' + object[temp_count + 1:]+','
            temp_flag = 1;
        else:
            temp_count = object.find(':')
            object = '],' + object[:temp_count + 1] + '[' + object[temp_count + 1:] + ','
    else:
        object = object + ',' 
    temp_list.append(object)
final_str = ''.join(temp_list)
final_str = final_str[:-2] + ']}'
print final_str

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2012-10-24
    • 2012-07-15
    • 2013-06-07
    相关资源
    最近更新 更多