尝试转储JSON时出错

时间:2017-12-17 11:07:02

标签: python json python-2.7

我在Python之前没有经验,除了近10年前我做过的一些乱七八糟的事情。我试图从OMDB API读取数据并在Python 2.7.14中继续出错。

这是应该返回的示例:

> {"Title":"The Matrix","Year":"1999","Rated":"R","Released":"31 Mar
> 1999","Runtime":"136 min","Genre":"Action, Sci-Fi","Director":"Lana
> Wachowski, Lilly Wachowski","Writer":"Lilly Wachowski, Lana
> Wachowski","Actors":"Keanu Reeves, Laurence Fishburne, Carrie-Anne
> Moss, Hugo Weaving","Plot":"A computer hacker learns from mysterious
> rebels about the true nature of his reality and his role in the war
> against its
> controllers.","Language":"English","Country":"USA","Awards":"Won 4
> Oscars. Another 34 wins & 45
> nominations.","Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg","Ratings":[{"Source":"Internet
> Movie Database","Value":"8.7/10"},{"Source":"Rotten
> Tomatoes","Value":"87%"},{"Source":"Metacritic","Value":"73/100"}],"Metascore":"73","imdbRating":"8.7","imdbVotes":"1,354,586","imdbID":"tt0133093","Type":"movie","DVD":"21
> Sep 1999","BoxOffice":"N/A","Production":"Warner Bros.
> Pictures","Website":"http://www.whatisthematrix.com","Response":"True"}

到目前为止,这是我的Python代码:

import requests
API_KEY = '******'
Movie = 'The Matrix'
results = requests.get("http://www.omdbapi.com/", 
              params={'apikey': API_KEY, 't': Movie})

我得到了结果。

在此阶段之后导入json后,我尝试运行json.dumps(结果),这给了我错误:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    json.dumps(results)
  File "C:\Python27\lib\json\__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "C:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Response [200]> is not JSON serializable

我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

results不是str,而是requests.models.Response个对象。尝试调用它的.json()方法,如下所示:

import requests
API_KEY = '******'
Movie = 'The Matrix'
results = requests.get("http://httpbin.org/get", 
              params={'apikey': API_KEY, 't': Movie})

data = results.json()

print data