我們經常需要處理 JSON 數據,有時候需要將 JSON 轉換成樹形數據,以便更好地進行分析和處理。在 C 語言中,我們可以使用該語言提供的 JSON 函數庫來實現這一目標。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <jansson.h> //定義樹節點結構體 struct TreeNode { char* key; json_t* value; struct TreeNode* left; struct TreeNode* right; }; //將 JSON 轉換成樹形結構 struct TreeNode* JSON_to_tree(json_t* root) { if (!json_is_object(root)) return NULL; struct TreeNode* node = malloc(sizeof(struct TreeNode)); node->key = NULL; node->value = root; node->left = node->right = NULL; const char* key; json_t* value; json_object_foreach(root, key, value) { struct TreeNode* child = JSON_to_tree(value); if (child == NULL) continue; child->key = strdup(key); if (node->left == NULL) { node->left = child; } else if (node->right == NULL) { node->right = child; } } return node; } int main() { char* json_string = "{ \"name\": \"Alice\", \"age\": 25, \"friends\": [ { \"name\": \"Bob\", \"age\": 30 }, { \"name\": \"Cathy\", \"age\": 28 } ] }"; json_error_t error; json_t* root = json_loads(json_string, 0, &error); struct TreeNode* tree = JSON_to_tree(root); //遍歷樹節點 struct TreeNode* node = tree; while (node != NULL) { if (node->key != NULL) { printf("%s: ", node->key); } switch (json_typeof(node->value)) { case JSON_OBJECT: printf("{ "); node = node->left; break; case JSON_ARRAY: printf("[ "); node->value = json_array_get(node->value, 0); break; case JSON_INTEGER: printf("%lld ", json_integer_value(node->value)); node = node->right; break; case JSON_STRING: printf("%s ", json_string_value(node->value)); node = node->right; break; case JSON_TRUE: printf("true "); node = node->right; break; case JSON_FALSE: printf("false "); node = node->right; break; case JSON_NULL: printf("null "); node = node->right; break; } } //釋放內存 json_decref(root); free(tree); return 0; }
上述代碼將 JSON 轉換成樹形結構,并遍歷輸出每個節點的值。其中,JSON_to_tree 函數負責將 JSON 轉換成樹形結構,使用了遞歸的方式完成。遍歷樹節點時,根據節點的值類型分別處理,可根據實際需求進行擴展。