Skip to content

Instantly share code, notes, and snippets.

@SijmenHuizenga
Last active October 20, 2017 17:52
Show Gist options
  • Save SijmenHuizenga/86dd667bcca4a33ba43f2fdd98fc7db7 to your computer and use it in GitHub Desktop.
Save SijmenHuizenga/86dd667bcca4a33ba43f2fdd98fc7db7 to your computer and use it in GitHub Desktop.
Json Parser in C++ (single level
//find the range of the value of a field by its id in JSON or NULL if not found. example:
// field "id" //including the " chars!
// json {"id": 417}
// response {7,9}
// String values are returned excluding their surrounding "
// This only works for single level json and array's are not supported.
int *findJsonFieldRange(const char *json, const char *field) {
int jsoni = 0;
int fieldi = 0;
//search for the field name. End when the full name is read.
while (1) {
if (json[jsoni] == field[fieldi])
fieldi++;
else
fieldi = 0;
jsoni++;
if (field[fieldi] == '\0')
break; //jsoni is now at the char after the field in the json. This must be a " char.
if (json[jsoni] == '\0')
return NULL; //field name not found
}
jsoni++;
//skip all whitespaces : to get to the value.
while (json[jsoni] == ' ' || json[jsoni] == '\t' || json[jsoni] == ':')
jsoni++;
int valueBegin = jsoni;
bool quoteTerminated = json[jsoni] == '"';
if(quoteTerminated)
valueBegin++;
jsoni++;
while (1) {
if (quoteTerminated) {
if (json[jsoni] == '"' && json[jsoni - 1] != '\\')
break;
} else {
if (json[jsoni] == ',' || json[jsoni] == '}'){
break;
}
}
jsoni++;
if (json[jsoni] == '\0')
return NULL; //field name not found
}
jsoni--; //the last char should not be included
int* out = new int[2];
out[0] = valueBegin;
out[1] = jsoni;
return out;
}
int main() {
const char *in = "{\"id4id\": 41.7, \"id2\": \"123\", \"id4\": \"aaa\\\"bbb\\\"ccc\"}";
int *result = findJsonFieldRange(in, "\"id4\"");
if(result != NULL)
for(int i = result[0]; i <= result[1]; i++){
printf("%c", in[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment