C语言不使用Cjson库将一下json串中的键值都提取出来{ "message":"", "reason":"", "res":{ "deviceInfo":null, "iotMqttInfo":null, "status":"NOTFOUND" }
时间: 2023-09-15 13:19:29 浏览: 19
#include <stdio.h>
#include <string.h>
int main() {
char json_str[] = "{ \"message\":\"\", \"reason\":\"\", \"res\":{ \"deviceInfo\":null, \"iotMqttInfo\":null, \"status\":\"NOTFOUND\" } }";
char key[20], value[20];
int i = 0, j = 0, k = 0, len = strlen(json_str);
while (i < len) {
if (json_str[i] == '"' && json_str[i - 1] != '\\') {
j = 0;
i++;
while (json_str[i] != '"' || json_str[i - 1] == '\\') {
key[j++] = json_str[i++];
}
key[j] = '\0';
printf("key: %s\n", key);
}
if (json_str[i] == ':' && json_str[i - 1] != '\\') {
j = 0;
i++;
while (json_str[i] == ' ' || json_str[i] == '\t' || json_str[i] == '\n') {
i++;
}
if (json_str[i] == '"') {
i++;
while (json_str[i] != '"' || json_str[i - 1] == '\\') {
value[j++] = json_str[i++];
}
value[j] = '\0';
printf("value: %s\n", value);
} else if (json_str[i] == '{' || json_str[i] == '[') {
k = 1;
i++;
while (k > 0) {
if (json_str[i] == '{' || json_str[i] == '[') {
k++;
} else if (json_str[i] == '}' || json_str[i] == ']') {
k--;
}
i++;
}
} else {
while (json_str[i] != ',' && json_str[i] != '}' && json_str[i] != ']') {
value[j++] = json_str[i++];
}
value[j] = '\0';
printf("value: %s\n", value);
}
}
i++;
}
return 0;
}
阅读全文