我有一个简单的服务器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