"a=&b=&c=***" 這種追加字符串在網(wǎng)絡(luò)協(xié)議里面很常見(jiàn):
現(xiàn)在有需求將其轉(zhuǎn)換為雙重鏈表或者 json 格式的字符串桅打,一般有需求當(dāng)然先谷歌丸凭,可是這種字符串也不知道學(xué)名是啥递礼,所以問(wèn)題不太好描述,那么只能自己動(dòng)手了馍悟。
其實(shí)用 python 處理的話仇轻,邏輯并不復(fù)雜,為了方便有相同需要的同學(xué)直接放代碼吧。
import copy
import logging
import traceback
logging.basicConfig(filename=__name__ + '.log')
def appendStr2JsonStr(src, itemSplitFlag='&', keyWordSplitFlag='='):
try:
jsonRet = "{"
# 分割各項(xiàng)
items = src.split(itemSplitFlag)
itemNames = list(items)
# 分割鍵值
for index in range(len(items)):
tmpItem = items[index]
itemNamesIndex = tmpItem.find(keyWordSplitFlag)
itemNames[index] = tmpItem[0:itemNamesIndex]
items[index] = tmpItem[itemNamesIndex + 1:]
# 拼接 json 字符串
for index in range(len(items)):
jsonRet += ('\"' + itemNames[index] + '\":\"' + items[index] + '\", ')
jsonRet = jsonRet[:-2]
jsonRet += '}'
return jsonRet
except BaseException, e:
s = traceback.format_exc()
logging.error(s)
return None
def appendStr2StrList(src, itemSplitFlag='&', keyWordSplitFlag='='):
try:
retList = []
tmpList = []
# 分割各項(xiàng)
items = src.split(itemSplitFlag)
itemNames = list(items)
# 分割鍵值
for index in range(len(items)):
tmpItem = items[index]
itemNamesIndex = tmpItem.find(keyWordSplitFlag)
itemNames[index] = tmpItem[0:itemNamesIndex]
items[index] = tmpItem[itemNamesIndex + 1:]
# 拼接雙重鏈表
for index in range(len(items)):
tmpList[:] = []
tmpList.append(itemNames[index])
tmpList.append(items[index])
retList.append(copy.deepcopy(tmpList))
return retList
except BaseException, e:
s = traceback.format_exc()
logging.error(s)
return None
效果圖: