Reputation: 1840
New to Python here so bear with me:
I'm using the awesome Requests module to make a POST request to Facebook Graph API. Here's my code:
#! /usr/bin/python
# -*- coding: utf-8 -*-
import requests
access_token = '9DYWNDXKPsTUkW1TcFZA5E1gUsIhliA0wMc0YZAmcu2Qtd8MtJVW50Y2ZBpnjkw8FH8d5LTmm7AuJ35pQo5'
fburl = 'https://graph-video.facebook.com/v2.3/56914066/videos?access_token='+str(access_token)
payload = {'upload_phase': 'start', 'file_size': '6999244'}
flag = requests.post(fburl, data=payload).text
print flag
I'm running this Python script locally on my Mac OSX machine, using Python 2.7, from Terminal. The response I get from the Facebook API, which is printed out in Terminal:
{"video_id":"635631120558","start_offset":"0","end_offset":"1048576","upload_session_id":"6356311891"}
Now, I assuming that:
This response is a dictionary, correct? And it's a JSON response?
I'm also assuming that that means the variable "flag" is a JSON object?
My big question: Should I be able to iterate through "flag" as a dictionary or JSON object?
Just a bit confused on what's being returned in Terminal and how I can deal with the "flag" variable in the code.
Upvotes: 0
Views: 1278
Reputation: 15336
Your code is calling the text
method of the requests
object, and so the (JSON) response is getting converted into a string, which you are then printing out. So you would not be able to iterate over that.
However, if you don't call text
, the resulting object should be a JSON object (based on a quick glance at the Facebook Graph API doc) that you can iterate over using the built-in json
module. See the Decoding JSON section.
e.g. if you import json
at the top of your code, you could then do something like this:
flagJson = requests.post(fburl, data=payload)
flagDict = json.loads(flagJson)
And then you can iterate over flagDict
as you would any other dict
.
Edit in response to follow-up comment from OP:
json.loads(flagJson)
decodes the JSON into a Python dict
which can then be used as any other dict
would. It all depends on what you want to do with it. Most likely, if you want to manipulate it in any way, you'll want to decode it, as then you can iterate over it, change values, write it out in another format, or encode it back into JSON with any changes you've made to it.
Upvotes: 2