cJSON遍历实例代码
时间: 2023-10-19 22:31:17 浏览: 110
Json 循环遍历解析示例代码
4星 · 用户满意度95%
cJSON遍历实例代码如下:
```c
#include <stdio.h>
#include "cJSON.h"
void traverse(cJSON *root) {
if (root == NULL) {
return;
}
switch (root->type) {
case cJSON_False:
printf("False\n");
break;
case cJSON_True:
printf("True\n");
break;
case cJSON_NULL:
printf("NULL\n");
break;
case cJSON_Number:
printf("Number: %lf\n", root->valuedouble);
break;
case cJSON_String:
printf("String: %s\n", root->valuestring);
break;
case cJSON_Array:
printf("Array:\n");
cJSON *child = root->child;
while (child != NULL) {
traverse(child);
child = child->next;
}
break;
case cJSON_Object:
printf("Object:\n");
cJSON *item = root->child;
while (item != NULL) {
printf("Key: %s\n", item->string);
traverse(item);
item = item->next;
}
break;
default:
break;
}
}
int main() {
const char *jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
cJSON *root = cJSON_Parse(jsonStr);
traverse(root);
cJSON_Delete(root);
return 0;
}
```
上述代码通过cJSON库解析了一个JSON字符串,并实现了遍历JSON对象的功能。遍历函数traverse()通过递归地遍历cJSON对象的子节点,根据节点的类型打印出相应的信息。在主函数中,我们首先将JSON字符串解析为cJSON对象,然后调用traverse()函数进行遍历,最后释放资源。
希望以上代码能对您有所帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [ESP32-C3入门教程 系统篇④——cJSON应用实例 | C语言中超轻量级JSON解析器](https://blog.csdn.net/kangweijian/article/details/124579543)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [cJSON方法详解](https://blog.csdn.net/jhyBOSS/article/details/108375390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文