酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

用c语言, 写出处理json格式的逻辑

以下是一个简单的 C 语言示例,用于解析简单的 JSON 字符串。这个示例只处理了包含字符串值的键值对形式的 JSON 数据,并且功能相对有限。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 解析 JSON 字符串中的键值对 void parseJson(char *jsonString) { char *key = NULL; char *value = NULL; // 查找 "key": "value" 格式 char *startKey = strstr(jsonString, "\""); if (startKey == NULL) { printf("Invalid JSON format\n"); return; } startKey++; char *endKey = strstr(startKey, "\""); if (endKey == NULL) { printf("Invalid JSON format\n"); return; } int keyLength = endKey - startKey; key = (char *)malloc(keyLength + 1); strncpy(key, startKey, keyLength); key[keyLength] = '\0'; // 跳过 ": " char *startValue = strstr(endKey, ": ") + 2; // 查找下一个 " char *endValue = strstr(startValue, "\""); if (endValue == NULL) { printf("Invalid JSON format\n"); free(key); return; } int valueLength = endValue - startValue; value = (char *)malloc(valueLength + 1); strncpy(value, startValue, valueLength); value[valueLength] = '\0'; printf("Key: %s, Value: %s\n", key, value); free(key); free(value); } int main() { char jsonString[] = "{\"name\": \"John\", \"age\": \"25\"}"; parseJson(jsonString); return 0; } ``` 这只是一个非常简单的示例,实际的 JSON 处理通常需要更复杂和健壮的实现,可能需要使用第三方库,如`cJSON`,来处理各种复杂的 JSON 格式和数据类型。 [2024-08-06 10:53:14 | AI写代码神器 | 499点数解答]

相关提问