NATS Logo by Example

JSON for Message Payloads in Messaging

The basic structure of a NATS message modeled in the client libraries includes the subject the message was published to, the application-defined payload, and an optional set of headers (for requests, there is also a reply-to subject). The payload is a sequence of bytes, so it is up to the application to define how to serialize and deserialize the payload.

JSON is ubiquitous and simple data-interchange format that is supported in virtually all programming languages. This example demonstrates how to serialize and deserialize a message payload using a JSON library.

CLI Go Python JavaScript Rust C# .NET V2 Java Ruby Elixir Crystal C
Jump to the output or the recording
$ nbe run messaging/json/deno
View the source code or learn how to run this example yourself

Code

import the library - in node.js import {connect, etc} from "nats"; or if not doing a module, const {connect, etc} = require("nats");

import { connect } from "https://deno.land/x/nats@v1.16.0/src/mod.ts";

Get the passed NATS_URL or fallback to the default. This can be a comma-separated string.

const servers = Deno.env.get("NATS_URL") || "nats://localhost:4222";

Create a client connection to an available NATS server.

const nc = await connect({
  servers: servers.split(","),
});

Create a subscription that receives two messages. One message will contain a valid serialized payload and the other will not.

const sub = await nc.subscribe("foo", { max: 2 });
(async () => {
  for await (const m of sub) {
    try {

payload of the message m.data is an Uint8Array m.json() parses the JSON payload - this can fail. m.string() parses the payload as a string

      console.log(m.json());
    } catch (err) {
      console.log(`err: ${err.message}: '${m.string()}'`);
    }
  }
})();

publish the messages

nc.publish("foo", JSON.stringify({ foo: "bar", bar: 27 }));
nc.publish("foo", "not json");


await nc.drain();

Output

[?25l[+] Building 0.0s (0/0)                                                                                                                                                                                                             
[?25h[?25l[+] Building 0.0s (0/0)                                                                                                                                                                                                             
[?25h{ foo: "bar", bar: 27 }
err: Bad JSON: 'not json'

Recording

Note, playback is half speed to make it a bit easier to follow.