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
robc
May 18, 2020, 1:06pm
6
Very nice. Works great, thanks!
mawrob
October 6, 2020, 6:50pm
7
This is great thanks. I had not noticed it.
Could you provide an example of creating a nested structure such as:
{
"f":
{
"g":"Call me \"John\"",
"h":-0.78
}
}
JsonWriterStatic<256> jw;
jw.startObject(); // Start outer object
jw.setFloatPlaces(2);
jw.insertKeyObject("f"); // Start inner object
jw.insertKeyValue("g", "Call me \"John\"");
jw.insertKeyValue("h", -.78);
jw.finishObjectOrArray(); // End inner object
jw.finishObjectOrArray(); // End outer object
The JSON created looks like:
{"f":{"g":"Call me \"John\"","h":-0.78}}
And if you run it through JSONLint in looks good:
1 Like
rickkas7
Closed
April 8, 2021, 12:24am
10
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.