Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python requests json returns single quote

i'm playing a little with google places api and requests

I got :

r = requests.get(self.url, params={'key': KEY, 'location': self.location, 'radius': self.radius, 'types': "airport"}, proxies=proxies)

r returns a 200 code, fine, but I'm confused by what r.json() returns compared to r.content

extract of r.json() :

{u'html_attributions': [], u'next_page_token': u'CoQC-QAAABT4REkkX9NCxPWp0JcGK70kT4C-zM70b11btItnXiKLJKpr7l2GeiZeyL5y6NTDQA6ASDonIe5OcCrCsUXbK6W0Y09FqhP57ihFdQ7Bw1pGocLs_nAJodaS4U7goekbnKDlV3TaL8JMr4XpQBvlMN2dPvhFayU6RcF5kwvIm1YtucNOAUk-o4kOOziaJfeLqr3bk_Bq6DoCBwRmSEdZj34RmStdrX5RAirQiB2q_fHd6HPuHQzZ8EfdggqRLxpkFM1iRSnfls9WlgEJDxGB91ILpBsQE3oRFUoGoCfpYA-iW7E3uUD_ufby-JRqxgjD2isEIn8tntmFDjzQmjOraFQSEC6RFpAztLuk7l2ayfXsvw4aFO9gIhcXtG0LPucJkEa2nj3PxUDl', u'results': [{u'geometry': {u'location': {u'lat': -33.939923, u'lng': 151.175276}},

while extract of r.content :

'{\n "html_attributions" : [],\n "next_page_token" : "CoQC-QAAABT4REkkX9NCxPWp0JcGK70kT4C-zM70b11btItnXiKLJKpr7l2GeiZeyL5y6NTDQA6ASDonIe5OcCrCsUXbK6W0Y09FqhP57ihFdQ7Bw1pGocLs_nAJodaS4U7goekbnKDlV3TaL8JMr4Xp

so r.content has the double quotes like a "correct" json object while r.json() seems to have changed all double-quotes in single-quotes.

Should I care about it or not ? I can still access r.json() contents fine, just wondered if this was normal for requests to return an object with single quotes.

like image 447
euri10 Avatar asked Oct 29 '15 15:10

euri10


Video Answer


2 Answers

What you can however is to add

jsonresponse=json.dump(requests.get(xxx).json())

in order to get valid json in jsonresponse.

like image 98
glmrenard Avatar answered Sep 29 '22 17:09

glmrenard


You are seeing the single quotes because you are looking at Python, not JSON.

Calling Response.json attempts to parse the content of the Response as JSON. If it is successful, it will return a combination of dicts, lists and native Python types as @Two-Bit Alchemist alluded to in his comment.

Behind the scenes, The json method is just calling complexjson.loads on the response text (see here). If you dig further to look at the requests.compat module to figure out what complexjson is, it is the simplejson package if it is importable on the system (i.e. installed) and the standard library json package otherwise (see here). So, modulo considerations about the encoding, you can read a call to Response.json as equivalent to:

import requests
import json

response = requests.get(...)
json.loads(response.text)

TL;DR: nothing exciting is happening and no, what is returned from Response.json is not intended to be valid JSON but rather valid JSON transformed into Python data structures and types.

like image 38
chucksmash Avatar answered Sep 29 '22 15:09

chucksmash