Rust: JSON stringify and parse in Node.js

I’m learning Rust for a project to build native modules for use with Node.js and it took me a bit of time to figure out how to parse and stringify JSON using serde_json and neon_serde. With Rust still being a relatively new language, the API of both the language and its crates have shifted over time making some of the older examples no longer useful. The solution I came up with using Rust 1.35 and Neon Bindings 0.2 follows.

Rust

[package]
name = "rust-json"

[lib]
name = "rust_json"
crate-type = ["dylib"]

[build-dependencies]
neon-build = "0.2.0"

[dependencies]
neon = "0.2.0"
'neon-serde' = "0.1.1"
serde_json = "1.0.39"
#[macro_use]
extern crate neon;
extern crate neon_serde;
extern crate serde_json;

use neon::prelude::*;

fn stringify(mut cx: FunctionContext) -> JsResult<JsString> {
  // get the argument as a JsValue (any json type)
  let value = cx.argument::<JsValue>(0)?;
  // convert to a serde Value
  let object: serde_json::Value = neon_serde::from_value(&mut cx, value)?;
  // convert to a String
  let string = serde_json::to_string(&object).unwrap();
  // return the JsString
  Ok(cx.string(string))
}

fn parse(mut cx: FunctionContext) -> JsResult<JsValue> {
  // get the argument as a string
  let string = cx.argument::<JsString>(0)?;
  // convert from serde Value to serde_json Value
  let object: serde_json::Value = serde_json::from_str(&string.value()).unwrap();
  // now convert to JsValue (any json type)
  let value = neon_serde::to_value(&mut cx, &object)?;
  / return the JsValue
  Ok(value)
}

register_module!(mut cx, {
  cx.export_function("stringify", stringify)?;
  cx.export_function("parse", parse)?;
  Ok(())
});

Node.js

const native = require('../native');
// more javascript logic here
module.exports = native;

You can now import this module as you would any other node module.

const rust = require('rust-json'); // or however you reference your module

const stringified = rust.stringify({ test: 123 });
console.log('stringified', stringified);

const parsed = rust.parse(stringified);
console.log('parsed', parsed);

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *