Last active
July 15, 2022 02:13
-
-
Save opsJson/c11d2aa2c6acc54bbc7b47f9ed05d20b to your computer and use it in GitHub Desktop.
Simple JSON Parser.
This file contains hidden or 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 <stdio.h> | |
#include <string.h> | |
#include <signal.h> | |
typedef struct json_t { | |
char *key; | |
char *value; | |
} json_t; | |
void _json_parse(int s) { | |
puts("ERROR: 'char *json' can't be a string literal or pointer!\n"); | |
} | |
int json_parse(char *json, json_t *parsed, int size) { | |
int i; | |
int length = strlen(json); | |
int inside_string = 0; | |
int inside_array = 0; | |
int inside_object = 0; | |
int count = 0; | |
json++; | |
signal(SIGSEGV, _json_parse); | |
for (i=0; i<length; i++) { | |
if (json[i] == '"' && json[i-1] != '\"') inside_string = !inside_string; | |
if (json[i] == '[') inside_array++; | |
if (json[i] == ']') inside_array--; | |
if (json[i] == '{') inside_array++; | |
if (json[i] == '}') inside_array--; | |
if (inside_string) continue; | |
if (inside_array) continue; | |
if (inside_object) continue; | |
if (json[i] == ':') json[i] = 0, count++; | |
if (json[i] == ',') json[i] = 0; | |
} | |
if (count > size) return -1; | |
for (i=0; i<count; i++) { | |
json[strlen(json)-1] = 0; | |
parsed[i].key = json + 1; | |
json += strlen(json) + 2; | |
parsed[i].value = json; | |
json += strlen(json) + 1; | |
} | |
json -= 2; | |
*json = 0; | |
return count; | |
} | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
int main(void) { | |
char json[] = "{\"foo\":\"bar\",\"object\":{\"foo\":\"bar\"},\"object\":{\"foo\":\"bar\"},\"object\":{\"foo\":\"bar\"},\"arr\":[1,2,3],\"str\":[\"123\",\"hhaha\"],\"foo\":\"bar\",\"foo\":\"bar\",\"arr\":[1,2,3],\"str\":[\"123\",\"hhaha\"],\"foo\":\"bar\"}"; | |
json_t p[50] = {{}}; | |
int count = json_parse(json, p, sizeof(p)/sizeof(*p)); | |
int i; | |
for (i=0; i<count; i++) | |
printf("[%s] => [%s]\n", p[i].key, p[i].value); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment