淘先锋技术网

首页 1 2 3 4 5 6 7

c json是一种轻量级的数据交换格式,它被广泛应用于前后端数据传输、网络通信、配置文件读取等场景。使用c json查询可以快速找到指定字段或数组元素,提高数据处理效率。

//示例1:从json字符串中获取指定字段的值
char *json_str = "{\"name\":\"小明\",\"age\":18,\"hobbies\":[\"reading\",\"music\"]}";
cJSON *root = cJSON_Parse(json_str);
cJSON *name = cJSON_GetObjectItem(root, "name"); //获取name字段
printf("%s的年龄是%d岁。", name->valuestring, cJSON_GetObjectItem(root, "age")->valueint);
//示例2:遍历json数组
cJSON *hobbies = cJSON_GetObjectItem(root, "hobbies"); 
cJSON *hobby = NULL;
cJSON_ArrayForEach(hobby, hobbies) { //遍历hobbies数组
printf("%s\n", hobby->valuestring); //获取数组元素的值
}
//示例3:嵌套查询
char *json_str2 = "{\"students\":[{\"name\":\"小红\",\"age\":19,\"scores\":[90,85,88]},{\"name\":\"小刚\",\"age\":20,\"scores\":[82,87,92]}]}";
root = cJSON_Parse(json_str2);
cJSON *students = cJSON_GetObjectItem(root, "students"); //获取students数组
cJSON *student = NULL;
cJSON_ArrayForEach(student, students) { //遍历students数组
cJSON *name = cJSON_GetObjectItem(student, "name"); //获取name字段
printf("%s的成绩为:", name->valuestring);
cJSON *scores = cJSON_GetObjectItem(student, "scores"); //获取scores数组
cJSON *score = NULL;
cJSON_ArrayForEach(score, scores) { //遍历scores数组
printf("%d ", score->valueint); //获取数组元素的值
}
printf("\n");
}

上述示例展示了c json查询的常见用法,通过掌握它们可以更加灵活、高效地对json数据进行处理。在实际开发中,我们需要根据业务需求灵活运用c json的各种接口,以便更好地完成数据处理任务。