Python处理Dict生成json
巴扎黑
巴扎黑 2017-04-18 10:33:02
0
3
913

情况是这样:
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"

谢谢!~

巴扎黑
巴扎黑

répondre à tous(3)
大家讲道理
# 无非就是list套dict,一层一层往下写就是了
# 输出正常的
for (k,v) in he.items():
    if k != 'unknown':
        print k,':',v[0]
    else:
        # unknown对应的值是list
        for it in v:
            # it是dict
            print it.get('key'), ':', it.get('value')[0]
左手右手慢动作

Pour apprendre à gérer les données avec élégance, supprimez simplement l'inconnu et fusionnez-le.

unknown = headers['unknown']
headers.pop('unknown')
set(map(lambda x: (x['key'], x['value'][0])))
headers = dict(headers.items() + unknown)
阿神
headers.update({_['key']: _['value'][0] for _ in headers['unknown']})
headers.pop('unknown')
print headers
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal