使用Python访问嵌套的JSON值 [英] Access nested JSON values using Python
问题描述
我正在尝试使用Python访问嵌套的JSON值.
I am trying to access a nested JSON value using Python.
这是我的JSON的摘录:
Here is an excerpt of my JSON:
{
"data": [
{
"name": "page_video_views",
"period": "day",
"values": [
{
"value": 634,
"end_time": "2018-11-23T08:00:00+0000"
},
{
"value": 465,
"end_time": "2018-11-24T08:00:00+0000"
}
],
"title": "Daily Total Video Views",
"description": "Daily: Total number of times videos have been viewed for more than 3 seconds. (Total Count)",
"id": "{page-id}/insights/page_video_views/day"
},
这是我到目前为止编写的代码:
Here is the code I have written so far:
import json
import urllib.request
data = urllib.request.urlopen("https://graph.facebook.com/v3.1/{page-id}/insights?access_token={access-token}&pretty=0&metric=page_impressions%2cpage_engaged_users%2cpage_fans%2cpage_video_views%2cpage_posts_impressions").read()
output = json.loads(data)
print(json.dumps(output, indent=2))
for item in output['data']:
name = item['name']
period = item['period']
value = item['data']['values']['value']
print(name, period, value)
我面临的问题是,每当我运行代码来访问名称"和句号"时,它就可以很好地工作,但是我无法访问值"中的值".我相信这是因为有两个价值"结果,我想每次都拉第一个.
The issue I am facing is that whenever I run the code to access 'name' and 'period' it works beautifully, but I cannot access 'value' in 'values'. I believe this is because there are two 'value' results, and I would like to pull the first one each time.
感谢您的帮助
推荐答案
item['data']['values']
是一个列表.您需要获取其第一个元素,然后才能访问其'value'
字段.也就是说,对应的行应为:
item['data']['values']
is a list. You need to get its first element and only then access its 'value'
field. That is, the corresponding line should be:
value = item['data']['values'][0]['value']
这篇关于使用Python访问嵌套的JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!