Deno nuggets: Respond with JSON
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to respond with JSON data in Deno?
$ curl http://localhost:8080 -v
> GET / HTTP/1.1
< HTTP/1.1 200 OK
< content-type: application/json
< content-length: 22{"text":"Hello world"}
Solution
JSON is undoubtedly the most popular data format used by APIs. Unless it’s a case of multipart bodies, JSON is the de-facto standard. JSON is a language-independent data format. It was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data.
With Deno v1.22, it has become very easy to respond with JSON data using the static method json() provided with the web standard Response interface. The static method json() returns a Response object with stringified JSON body and the correct setting of the content-type/content-length headers. The input is any JavaScript object.
Here is the code of a server that responds with JSON:
import { serve } from "https://deno.land/std/http/mod.ts";serve((_) => Response.json({ text: "Hello world from Deno!" }));
It’s a one-liner now! There is no longer a need to stringify and set the content-type header. All of that is taken care by Deno.
Here is the output of a sample run:
$ deno run --allow-net=:8000 app.ts$ curl http://localhost:8000
> GET / HTTP/1.1
>
< HTTP/1.1 200 OK
< content-type: application/json
< content-length: 33
{"text":"Hello world from Deno!"}