在C語言中,可以使用第三方庫來解析JSON數據格式,比如使用CJSON或者Jansson庫。
首先需要在代碼中引入相應的頭文件:
#include <stdio.h> #include <cjson/cJSON.h>
然后,可以根據JSON數據的格式,來取出需要的值。以下是一個示例JSON數據:
{ "name": "張三", "age": 20, "gender": "男", "scores": { "math": 80, "english": 90, "chinese": 70 }, "hobbies": ["reading", "music"] }
取出JSON數據中"name"的值:
cJSON *root = cJSON_Parse(json_data); cJSON *name = cJSON_GetObjectItem(root, "name"); char *name_str = name->valuestring; printf("name is %s\n", name_str);
取出JSON數據中"age"的值:
cJSON *root = cJSON_Parse(json_data); cJSON *age = cJSON_GetObjectItem(root, "age"); int age_num = age->valueint; printf("age is %d\n", age_num);
取出JSON數據中"scores"對象中"english"的值:
cJSON *root = cJSON_Parse(json_data); cJSON *scores = cJSON_GetObjectItem(root, "scores"); cJSON *english = cJSON_GetObjectItem(scores, "english"); int english_score = english->valueint; printf("english score is %d\n", english_score);
取出JSON數據中"hobbies"數組的第一個元素的值:
cJSON *root = cJSON_Parse(json_data); cJSON *hobbies = cJSON_GetObjectItem(root, "hobbies"); cJSON *first_hobby = cJSON_GetArrayItem(hobbies, 0); char *first_hobby_str = first_hobby->valuestring; printf("first hobby is %s\n", first_hobby_str);