Professional Documents
Culture Documents
Using STRSTR To Parse JSON Messages - Beningo Embedded Group
Using STRSTR To Parse JSON Messages - Beningo Embedded Group
An Introduction to strstr
“LED1_ON”
“LED1_OFF”
“MOTOR_ON”
Etc
A developer can easily setup a series of if/else if/else statements to look for
values in the JSON. For example, if I know that I am expecting a JSON
messages that have an attribute/value pair of:
“message” : “LED1_ON”
Or
“message” : “LED1_OFF”
I can write a simple if block that checks for these command messages as
follows:
else
In the above code, JSON_Buffer is a string buffer that contains the received
JSON message. We are using strstr to search this buffer for known command
values that our embedded applications are interested in knowing about. We
then have a string that we are searching the buffer for. If strstr returns NULL,
it means that it did not find our string of interest. If it isn’t NULL, then it
returns a pointer to the first occurrence of the string we are searching for in
the JSON_Buffer.
Using if/else if/ else statements to parse JSON messages for strings of interest
is useful but if there are dozens of strings we are interesting in searching for
this can get a bit out of hand rather quickly. An alternative is to instead create
a table of strings and then use a for loop or a for loop. For example, we can
use a while loop that would look something like the following:
Once you know what index the string is at, you can then execute a function
pointer associated with the string to execute a function for the command. Just
make sure that you verify that the function pointer is not NULL before
dereferencing it.
Conclusions
In the past, developers used to be able to ignore the C libraries string
functions because we didn’t work with strings! However, that has now
dramatically changed since many developers are now working with IoT
connected devices and these devices pass human readable strings back and
forth using JSON. There are many ways to parse these messages but strstr is
a quick and simple method that developers can start with. More sophisticated
parsing algorithms can then be implemented later as they are needed.