【发布时间】:2017-12-22 10:02:00
【问题描述】:
我有一个简单的服务器from here,当调用GET函数时,我希望它返回一个JSON文件,如下面的相关代码sn-p所示:
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)
我是否在 do_GET 函数中正确加载了 test.json 文件?
感谢您的帮助:)
【问题讨论】:
-
如果要将 JSON 传递回客户端,为什么要在服务器上解析它?就做
with open('test.json') as data_file: self.wfile.write(data_file.read()) -
现在可以使用了,谢谢!我知道我这样做很尴尬:/请随意提交它作为答案!
标签: python json python-requests