Last active
February 1, 2021 18:17
-
-
Save jshep321/2b9ffb745edfa9dc121257656d811a07 to your computer and use it in GitHub Desktop.
Test filtering in ArduinoJson library on ESP32
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include <ArduinoJson.h> | |
void setup() { | |
Serial.begin(115200); | |
delay(1000); | |
int waittime = 3; //wait in seconds | |
Serial.println("Waiting " + String(waittime) + " seconds"); | |
for (int i=0; i<waittime; i++) | |
{ | |
delay(1000); | |
Serial.println("waiting..."); | |
} | |
String fullUserDB = ("{\"USER1\": { \"data\" : { \"1\" : \"item 1 description\", \"2\" : \"item 2 description\"}, \"associated user data\" : \"value\"}, \"USER2\": { \"data\" : { \"10\" : \"item 10 description\", \"11\" : \"item 11 description\"} ,\"associated user data\" : \"value\"}}"); | |
Serial.println("-----------initial json input string: -----------\n" + fullUserDB); | |
DynamicJsonDocument jsonDoc(2000); //jsonDoc to hold the DB | |
//deserialize and reserialize to prettify | |
DeserializationError err = deserializeJson(jsonDoc, fullUserDB); | |
String prettyUserDB; | |
serializeJsonPretty(jsonDoc, prettyUserDB); | |
Serial.println("-----------fullUserDB after prettify (no filter yet): -----------"); | |
Serial.println(prettyUserDB); | |
jsonDoc.clear(); //empty for reuse | |
//make the filter -- ideally I want to keep the target data of "10" and associated higher levels only --> { USER2, data : {10 : item 10 description}, associated user data: value } <-- | |
DynamicJsonDocument filter(1000); | |
filter["*"]["data"]["10"] = true; | |
Serial.println("make a filter -- \nideally I want to keep the target data of \"10\" and associated higher levels only \n--> { USER2, data : { 10 : item 10 description }, associated user data: value } <--"); | |
Serial.println("Filter: \nfilter[\"*\"][\"data\"][\"10\"] = true"); | |
//deserialize again -- this time apply filter | |
err = deserializeJson(jsonDoc, fullUserDB, DeserializationOption::Filter(filter)); | |
if (err) | |
{ | |
Serial.println("unable to deserialize DB"); | |
Serial.println("Error: " + String(err.c_str())); | |
} | |
//reserialize for viewing | |
String postFilterJson; | |
//serializeJson(jsonDoc, postFilterJson); | |
serializeJsonPretty(jsonDoc, postFilterJson); | |
Serial.println("-----------filtered userDB after pretty+filter: -----------"); | |
Serial.println(postFilterJson); | |
Serial.println("Result: Keeping unwanted USER1 and truncated wanted associated user data"); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment