簡體   English   中英

cJSON 鍵值解析

[英]cJSON Key-Value Parsing

我正在使用 cJSON 解析存儲在testdata.json文件中的 JSON 文件,如下所示:

{
    "text": "HelloWorld!!",
    "parameters": [{
            "length": 10
        },
        {
            "width": 16
        },

        {
            "height": 16
        }
    ]
}

通過以下內容,我可以訪問text字段。

int main(int argc, const char * argv[]) {

    //open file and read into buffer

    cJSON *root = cJSON_Parse(buffer);
    char *text = cJSON_GetObjectItem(root, "text")->valuestring;
    printf("text: %s\n", text); 
}

注意:這些參數是動態的,因為根據 JSON 文件包含的內容,可以有更多參數,例如volumearea等。 這個想法是我有一個包含所有這些參數的struct ,我必須檢查 JSON 中提供的參數是否存在並相應地設置值。 struct看起來像:

typedef struct {
   char *path;
   int length;
   int width;
   int height;
   int volume;
   int area;
   int angle;
   int size;
} JsonParameters;

我試着這樣做:

cJSON *parameters = cJSON_GetObjectItem(root, "parameters");
int parameters_count = cJSON_GetArraySize(parameters);
printf("Parameters:\n");
for (int i = 0; i < parameters_count; i++) {

    cJSON *parameter = cJSON_GetArrayItem(parameters, i);
    int length = cJSON_GetObjectItem(parameter, "length")->valueint;
    int width = cJSON_GetObjectItem(parameter, "width")->valueint;
    int height = cJSON_GetObjectItem(parameter, "height")->valueint;
    printf("%d %d %d\n",length, width, height);
}

這將返回Memory access error (memory dumped)加上我必須 state 是什么鍵。 如前所述,我不知道參數是什么。

如何存儲鍵值對( "length":10"width":16"height":16等)以及如何根據JsonParameters中的有效參數檢查鍵?

這是一個示例程序,它從示例 JSON 中遍歷parameters數組的所有元素,並打印出數組中每個 object 的字段名稱:

#include <stdio.h>
#include <cJSON.h>

int main(void) {
  const char *json_string = "{\"text\":\"HelloWorld!!\",\"parameters\":[{\"length\":10},{\"width\":16},{\"height\":16}]}";

  cJSON *root = cJSON_Parse(json_string);
  cJSON *parameters = cJSON_GetObjectItemCaseSensitive(root, "parameters");
  puts("Parameters:");
  cJSON *parameter;
  cJSON_ArrayForEach(parameter, parameters) {
    /* Each element is an object with unknown field(s) */
    cJSON *elem;
    cJSON_ArrayForEach(elem, parameter) {
      printf("Found key '%s', set to %d\n", elem->string, elem->valueint);     
    }
  }

  cJSON_Delete(root);
  return 0;
}

您可以將每個字段名稱與您關心的字段列表進行比較(簡單的方法是一堆if / else ifstrcmp() ),為每個字段設置適當的結構字段。

這里重要的是使用cJSON_ArrayForEach宏來遍歷數組的兩個元素(cJSON 表示 JSON arrays 作為鏈表,並像在代碼中一樣通過索引獲取每個元素使得遍歷數組成為O(N^2)操作,同時這個宏是O(N) ),以及數組中每個 object 的元素,因為您事先不知道哪些字段在哪個 object 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM