Hey there I am working on a Basic server with Python now I am testing out how I can return JSON data, but then now I am failing to return that JSON data.
This is how I am trying to send back JSON to client:
JavaScript
x
9
1
response= {
2
"name":'junior',
3
"name":'junior'
4
}
5
self.send_response(200)
6
self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
7
self.send_header('Content-type', 'application/json')
8
self.end_headers()
9
Below is the entire source code:
JavaScript
1
29
29
1
import ast
2
import json
3
from http.server import HTTPServer, BaseHTTPRequestHandler
4
from http import HTTPStatus
5
6
class ServiceHandler(BaseHTTPRequestHandler):
7
8
def do_GET(self):
9
print(self.path)
10
11
12
def do_POST(self):
13
content_len = int(self.headers.get('Content-Length'))
14
post_body = self.rfile.read(content_len)
15
body = ast.literal_eval(post_body.decode("utf-8"))
16
response= {
17
"name":'junior',
18
"name":'junior'
19
}
20
self.send_response(200)
21
self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
22
self.send_header('Content-type', 'application/json')
23
self.end_headers()
24
25
26
#Server Initialization
27
server = HTTPServer(('127.0.0.1',8080), ServiceHandler)
28
server.serve_forever()
29
Can I please get some help on how I can return back JSON data
Advertisement
Answer
Send headers before the body like this:
JavaScript
1
5
1
self.send_response(200)
2
self.send_header('Content-type', 'application/json')
3
self.end_headers()
4
self.wfile.write(bytes(json.dumps(response, ensure_ascii=False), 'utf-8'))
5