4

Python で HTTP リクエストを使用すると、レスポンスを取得できましたが、json モジュールも simplejson モジュールもそれをアンパッケージできませんでした。どちらも、入力が適切なjsonではないと主張しています。

import requests
import json

html_base = u"http://www.google.com/trends/fetchComponent?q="
q = u"asdf,qwerty"
query_type = u"&cid=TIMESERIES_GRAPH_0&export=3"
full_query = html_base + q + query_type

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

エラー:

C:\Anaconda\lib\json\decoder.pyc in raw_decode(self, s, idx)
    382             obj, end = self.scan_once(s, idx)
    383         except StopIteration:
--> 384             raise ValueError("No JSON object could be decoded")
    385         return obj, end

ValueError: No JSON object could be decoded
4

2 に答える 2

3

私のネクロマンシーを許してください、しかし、これは将来この方法でつまずくべき人のためのきれいな回避策です.

import ast

nice_dict = ast.literal_eval(response.text.split('setResponse(')[1].rstrip()[:-2].replace('new Date', ''))

ast.literal_eval()は文字列を取り、dict を返します。内部のすべてが json をクリーンアップして、返せるようにします。日付がタプルになっていることに注意してください。

于 2015-05-13T17:05:12.377 に答える