JSON Parser and Generator in Device OS

Did you know that there has been a JSON parser and generator built into Device OS since 0.6.1? It’s now documented!

Instead of having to do this:

int a = 123;
bool b = true;
const char *c = "testing";

snprintf(buf, sizeof(buf), "{\"a\":%d,\"b\":%s,\"c\":\"%s\"}", 
    a, 
    b ? "true" : "false",
    c);

You can now do this, which is much more readable and only adds 240 bytes of code.

JSONBufferWriter writer(buf, sizeof(buf) - 1);
writer.beginObject();
    writer.name("a").value(a);
    writer.name("b").value(b);
    writer.name("c").value(c);
writer.endObject();
writer.buffer()[std::min(writer.bufferSize(), writer.dataSize())] = 0;

Documentation:

https://docs.particle.io/reference/device-os/firmware/#json

12 Likes

Will be looking into this further, but could you possibly give some advantages/disadvantages of using the built in library vs your own JsonParserGeneratorRK library?

The biggest advantage of the built-in one is code size, since the JSMN parser is built into Device OS, not user firmware.

JsonParserGeneratorRK has some additional features that may make continuing to use it worthwhile if you are not short on code space:

  • Easy access to object values by key name
  • Easy access to array values by index
  • Fluent accessors for nested objects and arrays
  • Unicode UTF-8 support
1 Like

MAGICAL! no more errors like escaping this double quote here or there.
Thanks Rick

1 Like

in order to bring more awareness to it, do you guys think it can make it to the next release notes?
@rickkas7 @avtolstoy
thanks

Very nice. Works great, thanks!