2014-05-01 46 views
-1

我有一個字符串,它看起來像以下:編碼爲JSON從非結構化字符串

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

我不得不將其轉換爲JSON如下:

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

有沒有辦法做到這一點?

+0

什麼產生字符串?你可以*它*產生有效的JSON? – chepner

+0

你有什麼困難?你需要指導如何開始?根據您的需要,您可以使用正則表達式或解析器生成器(例如pyparsing)將字符串解析爲字典或(更糟糕的)插入括號以使其成爲有效的json – jfs

回答

0
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