Jenaro Calviño Jenaro Calviño - 1 year ago 196
JSON Question

How to translate json data to python object - Flask

I'm trying to do a web application using the OAuthlib to login with google, this is what the google object looks like:

google = oauth.remote_app('google',
request_token_params={'scope': 'email'},
consumer_key="my consumer",
consumer_secret="my secret",

The problem I hve is when I get the user information from google, his is my authorization view:

def authorized():
resp = google.authorized_response()
id_token = json.load(resp['id_token'])
login_user(me, True)
return redirect(url_for('index'))

So, what I try to do with the json.load is to decode the information google gives me, in this particular case, the response has an id_token which is a long string that, according to my research, is a json encoded string that when it is decoded, provides all the user information, no matter how much I try I can't seem to find the correct way to decode it, the error I get is:

AttributeError: 'unicode' object has no attribute 'read'

On the json.load line.

EDIT: after decoding the id_token I would then use it to get or create the user in my own database.

I am using Flask and the library is json.

If anyone could explain the correct way to decode the string into a python object I would appreciate it a lot, or if this is not json but some other type of coded string please do tell. Thank you very much in advance.

Answer Source

json.load reads from a file. To decode a JSON string, use json.loads.

However, according to these docs, id_token is not JSON, but a "JSON Web Token".

If you are looking for the "payload", you might try:

payload = json.loads( resp['id_token'].split('.')[1].decode('base64') )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download