我有一個簡單的服務器from here,當GET函數被調用時,我想它在下面的相關代碼段返回一個JSON文件,如顯示返回:使用JSON GET請求從服務器
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
self._set_headers()
with open('test.json') as data_file:
data = json.load(data_file)
self.wfile.write(data)
我的JSON文件:
{"foo": "bar", "boo": "far"}
請求文件(client.py)申請:
import requests
import json
r = requests.get('http://localhost:8080')
print r.json()
但是,試圖運行client.py我收到以下錯誤時:
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
我是正確加載test.json文件中的do_GET功能?不需要
感謝您的幫助:)
爲什麼您的服務器上解析JSON,如果你想送它回給客戶?只要用open('test.json')做data_file:self.wfile.write(data_file.read())' – zwer
它現在可以工作了,謝謝!我知道我是在做一個尷尬的方式:/隨意提交它作爲答案! – monadoboi