2017-07-31 113 views
0

我餵了以下數據,以我的python腳本作爲參數:Python的處理嵌套JSON

source=Blabla|| 
name=TEST Error in Log - Error: 3345|| 
item_value={ "Error": 3345, "Message": "Some error occurred", "Status": 1 } 

腳本:

#!/usr/bin/env python 
import sys, json 
data=sys.argv[3] 
if 'NOTE: Escalation cancelled' in data: 
     exit(0) 
data=data.split('||') 
datadictionary = {} 
for item in data: 
     key, val = item.split("=", 1) 
     k=key.strip() 
     v=(((((val.strip())).replace('\n',"<br>")).replace("`", "&lsquo"))) 
     datadictionary[ k ] = v 

datajson = json.dumps(datadictionary) 
datajson=datajson.encode('utf8') 

print(datajson) 

它提供了以下的輸出:

{"source": "Blabla", "name": "TEST Error in Log - Error: 3345", "item_value": "{ \"Error\": 3345, \"Message\": \"Some error occurred\", \"Status\": 1 }"} 

這不是一個合適的JSON,因爲item_value是一個字符串而不是JSON對象。我如何在這裏生成嵌套的JSON?

回答

0

我想通了,我需要先通過下面一行首先解碼JSON對象:

datadictionary['item_value']=json.loads(datadictionary['item_value']) 

所以劇本是這樣的:

#!/usr/bin/env python 
import sys, json 
data=sys.argv[3] 
if 'NOTE: Escalation cancelled' in data: 
     exit(0) 
data=data.split('||') 
datadictionary = {} 
for item in data: 
     key, val = item.split("=", 1) 
     k=key.strip() 
     v=val.strip().replace('\n',"<br>").replace("`", "&lsquo") 
     datadictionary[ k ] = v 

datadictionary['item_value']=json.loads(datadictionary['item_value']) 
datajson = json.dumps(datadictionary) 
datajson=datajson.encode('utf8') 


print(datajson) 

和輸出:

{"source": "Blabla", "name": "TEST Error in Log - Error: 3345", "item_value": {"Status": 1, "Message": "Some error occurred", "Error": 3345}}