C. The JSON Streaming Parser Library
Why would we want to use a streaming parser on the ESP8266? Embedded devices usually
have very limited resources available. One scarce resource is the heap memory. Many of the
REST APIs I am using in my projects provide big response objects, but we are usually just
interested in a small fraction of it. As mentioned earlier, a tree-based parser would load the
whole document into memory and make it available once the document stream has ended.
And this would just crash the ESP8266 pretty quickly; it does not have the resources to keep
200kb on the heap.
This made me port a PHP JSON parser over to C++ and make it available as a library, mostly
to be used in my own projects. Let's have a look at the header file of the JsonListener:
1
class JsonListener {
2
public:
3
virtual void whitespace(char c) = 0;
4
virtual void startDocument() = 0;
5
virtual void key(String key) = 0;
6
virtual void value(String value) = 0;
7
virtual void endArray() = 0;
8
virtual void endObject() = 0;
9
virtual void endDocument() = 0;
10
virtual void startArray() = 0;
11
virtual void startObject() = 0;
12
};
The methods here are callback methods which will get invoked if the respective event
happens while parsing the document. Let's start with an example. For the JSON object
"Eichhorn"} we get the following invocations:
⚫
startDocument(): we start receiving a json document
⚫
startObject(): the json object starts with "{"
⚫
key("name"): the parser detected a key object which contains "name"
⚫
value("Eichhorn"): the parser detected a value containing "Eichhorn"
⚫
endObject(): the object ends with "}"
⚫
endDocument(): the stream of data ends and so does the document
I often just implement (AKA "write code") for the
method I store the value of the key parameter. Then later in the
key()
and the
value()
value()
{"name":
methods. In the
key()
method I check what
Need help?
Do you have a question about the ESP8266 and is the answer not in the manual?
Questions and answers