搜索

首页  >  问答  >  正文

Python处理Dict生成json

情况是这样:
json文件中存在一个值为

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<code>"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"]}

    ]

}</code>

由于之前的脚本的处理过于简单粗暴。现实要将"unknown"给替换成字典中的值。
以下是我处理的一段Test code ,在Ipython中:

1

2

3

4

5

6

7

8

9

10

<code>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]

</code>

输出的是:

1

2

3

4

5

6

7

<code>    "connection":"close",

    "content_language":"en",

    "content_length":"3137",

    "content_type":"text/html",

    "server":"squid/3.1.23",

    "unknown":[

      {"value":["1.0"],"key":"mime_version"}</code>

问题:
1, 怎么处理“unknown”中的list,用for的话,怎么输出?
2, 怎么处理“unknown”使其能输出如下的结果:

1

2

3

4

5

6

7

8

9

10

<code>    "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"</code>

谢谢!~

巴扎黑巴扎黑2880 天前1019

全部回复(3)我来回复

  • 大家讲道理

    大家讲道理2017-04-18 10:35:02

    雷雷

    回复
    0
  • ringa_lee

    ringa_lee2017-04-18 10:35:02

    要学会优雅的处理数据,只要把unknown 取出来再合并进去就行了。

    1

    2

    3

    4

    <code>unknown = headers['unknown']

    headers.pop('unknown')

    set(map(lambda x: (x['key'], x['value'][0])))

    headers = dict(headers.items() + unknown)</code>

    回复
    0
  • 阿神

    阿神2017-04-18 10:35:02

    雷雷

    回复
    0
  • 取消回复