Last active
December 5, 2022 06:49
-
-
Save vgrichina/4f3f265968d6b2535fb781d386f1097a to your computer and use it in GitHub Desktop.
chatGPT parse json lazy
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
// Tokenize the JSON string by splitting on `{`, `}`, `[`, and `]`, unless the character is inside a string | |
char* token = strtok(jsonCopy, "{}[],"); | |
bool inString = false; | |
int depth = 0; | |
while (token != NULL) { | |
if (!inString && depth == 0 && strcmp(token, path) == 0) { | |
// The requested path was found, so return the next token as the value | |
token = strtok(NULL, "{}[],"); | |
slice_t value = { | |
.len = strlen(token), | |
.data = token | |
}; | |
free(jsonCopy); | |
return value; | |
} | |
if (strcmp(token, "{") == 0 || strcmp(token, "[") == 0) { | |
// Increase the depth when entering a nested object or array | |
depth++; | |
} else if (strcmp(token, "}") == 0 || strcmp(token, "]") == 0) { | |
// Decrease the depth when exiting a nested object or array | |
depth--; | |
} else if (strcmp(token, "\"") == 0) { | |
// Toggle the inString flag when entering or exiting a string | |
inString = !inString; | |
} | |
// Get the next token | |
token = strtok(NULL, "{}[],"); | |
} | |
// The requested path was not found, so return an empty slice | |
free(jsonCopy); | |
return (slice_t) {0}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment