How to validate a JSON document?
ArduinoJson never intended to be a JSON validation library, so it doesn’t provide any built-in solution. However, you can use the following function to test whether a JSON string seems valid.
This solution doesn’t detect all errors but should be good enough for most projects.
// Returns true if input points to a valid JSON string
bool validateJson(const char* input) {
StaticJsonDocument<0> doc, filter;
return deserializeJson(doc, input, DeserializationOption::Filter(filter)) == DeserializationError::Ok;
}
As you can see, it uses a null filter to skip all the values in the input.
Without this filter deserializeJson()
would return NoMemory
.
Because deserializeJson()
is skipping the values, it will oversee many errors in the input.
Thank you to Jeroen Döll for finding this technique.