情况是这样:
json文件中存在一个值为
"headers":{ "connection":["close"], "content_language":["en"], "content_length":["3137"], "content_type":["text/html"], "server":["squid/3.1.23"], "unknown":[ {"key":"mime_version","value":["1.0"]}, {"key":"date","value":["Sat, 25 Mar 2017 06:11:38 GMT"]}, {"key":"x_squid_error","value":["ERR_INVALID_URL 0"]}, {"key":"x_cache","value":["MISS from unknown"]}, {"key":"x_cache_lookup","value":["NONE from unknown:8080"]} ] }
由于之前的脚本的处理过于简单粗暴。现实要将"unknown"给替换成字典中的值。
以下是我处理的一段Test code ,在Ipython中:
import json f = open('file.json','r') test_line = f.readline() jsonstr = json.loads(test_line) he = jsonstr['headers'] # 输出正常的 for (k,v) in he.items(): print k,':',v[0]
输出的是:
"connection":"close", "content_language":"en", "content_length":"3137", "content_type":"text/html", "server":"squid/3.1.23", "unknown":[ {"value":["1.0"],"key":"mime_version"}
问题:
1, 怎么处理“unknown”中的list,用for的话,怎么输出?
2, 怎么处理“unknown”使其能输出如下的结果:
"connection":"close", "content_language":"en", "content_length":"3137", "content_type":"text/html", "server":"squid/3.1.23", "mime_version":"1.0", "date":"Sat, 25 Mar 2017 06:11:38 GMT", "x_squid_error":"ERR_INVALID_URL 0", "x_cache":"MISS from unknown", "x_cache_lookup":"NONE from unknown:8080"
谢谢!~
要学会优雅的处理数据,只要把unknown 取出来再合并进去就行了。