1

I am trying to access a nested JSON value using Python.

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.

Thanks for the help

1 Answer 1

6

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']
Sign up to request clarification or add additional context in comments.

3 Comments

You're the master my friend. It actually worked on value = item['values'][0]['value']
Remember to accept his answer so other people can see that this is what solves the problem! ;)
Sorry about that! It was answered within 9 minutes so I had to wait and got a little distracted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.