barciewicz
barciewicz

Reputation: 3813

Get JSON response in Python, but in original JavaScript format

I am putting a JSON response into a variable via requests.json() like this:

response = requests.get(some_url, params=some_params).json()

This however converts JSON's original " to Python's ', true to True, null to None.

This poses a problem when trying to save the response as text and the convert it back to JSON - sure, I can use .replace() for all conversions mentioned above, but even once I do that, I get other funny json decoder errors.

Is there any way in Python to get JSON response and keep original JavaScript format?

Upvotes: 1

Views: 212

Answers (2)

tevemadar
tevemadar

Reputation: 13225

json() is the JSON decoder method. You are looking at a Python object, that is why it looks like Python.

Other formats are listed on the same page, starting from Response Content

  • .text: text - it has no separate link/paragraph, it is right under "Response Content"
  • .content: binary, as bytes
  • .json(): decoded JSON, as Python object
  • .raw: streamed bytes (so you can get parts of content as it comes)

You need .text for getting text, including JSON data.

Upvotes: 1

Reupiey
Reupiey

Reputation: 277

You can get the raw text of your response with requests.get(some_url, params=some_params).text

It is the json method which converts to a Python friendly format.

Upvotes: 1

Related Questions