I am reading the following nested dictionary in json from an API
{
"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"
}]
}
I need to filter the data based on two from and two dates. opened_at
is the value containing the date info.
My attempt so far is as follows
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)
I get the below error on running the code
AttributeError: 'list' object has no attribute 'items'
I know that the type of data['result'] is a list.Any help will be appreciated. Thanks!
data['result']
is a list of dictionaries, you should iterate on it like follows:
for d in data['result']:
for k, v in d.items():
you need this
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
Actually "Result" is a dictionnary. You can recognize a dictionnary in Python by the "{" and "}" it is circled with. So here it is a dictionnary of a list of dictionnaries !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.