Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of type Response is not JSON serializable

I am trying to convert my json from an api to a dataframe in python. I run the following codes:

import requests
import pandas as pd
import simplejson as json

params = {
  "api_key": "abc",
  "format": "json"
}
r = requests.get('https://www.parsehub.com/api/v2/runs/ttx8PT-EL6Rf/data', params=params)

data = json.dumps(r) #convert to json
data = json.loads(data)
dataFrame = pd.DataFrame.from_dict(data) #convert json to dataframe
print(dataFrame)

and I got these errors:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/test/convert jsontodataframe.py", line 11, in <module>
    data = json.dumps(r) #convert to json
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\simplejson\__init__.py", line 395, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\simplejson\encoder.py", line 296, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\simplejson\encoder.py", line 378, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\simplejson\encoder.py", line 273, in default
    o.__class__.__name__)
TypeError: Object of type Response is not JSON serializable

can you help me please. Is there another way I can convert my json api to a dataframe in python? Please help me.

like image 602
Nedisha Avatar asked Feb 09 '20 17:02

Nedisha


People also ask

How do I fix the object of type datetime is not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method.

Is not JSON serializable?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

Why is set not JSON serializable?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json. dumps(list(my_set)) . Here is an example of how the error occurs.

What is Jsonify in Python?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data. This could lead to unintended results.

How do I fix object of type set is not JSON serializable?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json.dumps (list (my_set)).

How to solve the Python TypeError object of type set is not JSON?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json.dumps (list (my_set)). Here is an example of how the error occurs.

How to make class JSON serializable in Python?

Write custom JSONEncoder to make class JSON serializable. Python json module has a JSONEncoder class. You can extend it If you want more customized output. i.e., you will have to subclass JSONEncoder so you can implement your custom JSON serialization. The json.dump() and json.dumps() method of the JSON module has a cls kwarg.

Why JSON stringify method does not serialize functions?

The JSON.stringify method does not serialize functions and other non-primitives because that are not valid JSON. MS in Data Science online—No GRE Required.


2 Answers

Remove this line:

data = json.dumps(r) #convert to json

This converts a python dictionary to a string - not a string to a json object as you have annotated in your code.

Your code should look like this:

import requests
import pandas as pd
import simplejson as json

params = {
  "api_key": "abc",
  "format": "json"
}

r = requests.get('https://www.parsehub.com/api/v2/runs/ttx8PT-EL6Rf/data', params=params)

data = json.loads(r.json)
dataFrame = pd.DataFrame.from_dict(data) #convert json to dataframe
print(dataFrame)
like image 188
Daniel Avatar answered Oct 10 '22 04:10

Daniel


r.json() is an already decoded Python object. Here's an example from a site without an API key:

import requests
import pandas as pd
import json

params = {"s": "margarita"}

r = requests.get('https://www.thecocktaildb.com/api/json/v1/1/search.php', params=params)

data = r.json()
dataFrame = pd.DataFrame.from_dict(data['drinks'])
print(dataFrame)

Output:

  idDrink                      strDrink  ... strCreativeCommonsConfirmed         dateModified
0   11007                     Margarita  ...                         Yes  2015-08-18 14:42:59
1   11118                Blue Margarita  ...                         Yes  2015-08-18 14:51:53
2   17216             Tommy's Margarita  ...                          No  2017-09-02 18:37:54
3   16158            Whitecap Margarita  ...                          No  2015-09-02 17:00:22
4   12322          Strawberry Margarita  ...                          No  2015-08-18 14:41:51
5  178332  Smashed Watermelon Margarita  ...                          No                 None

[6 rows x 51 columns]
like image 1
Mark Tolonen Avatar answered Oct 10 '22 03:10

Mark Tolonen