2012/06/25

JSON parser in C language - json-c

C 語言存取 JSON 格式的資料實在不是很方便,不像 python、javascript 原生的物件表示法就跟 JSON 一樣。C 的 implementation 在官網列了好幾套,我自己是選用 json-c

API 使用方式可以參考這裡

這邊就列出基本的操作,以這樣為例:
{
  "name": "Brian",
  "sex": 0,
  "data": {
    "education": "master",
    "profession": "engineer"
  }
}

組成 JSON object,並輸出成 string
struct json_object *root, *data;

root = json_object_new_object();
json_object_object_add(root, "name", json_object_new_string("Brian"));
json_object_object_add(root, "sex", json_object_new_int(0));

data = json_object_new_object();
json_object_object_add(data, "education", json_object_new_string("master"));
json_object_object_add(data, "profession", json_object_new_string("engineer"));
json_object_object_add(root, "data", data);

// Output to string
printf("%s", json_object_to_json_string(root));

// Decrease counter and free object
json_object_put(data);
json_object_put(root);

解開 JSON object
struct json_object *root, *name, *sex, *data, *edu, *prof;

root = json_tokener_parse(json_string);
// Use is_error() to check the result, don't use "j_root == NULL".
if (is_error(j_root)) {
  printf("parse failed.");
  exit(-1);
}

name = json_object_object_get(root, "name");
sex = json_object_object_get(root, "sex");
data = json_object_object_get(root, "data");
// If parse fail, object is NULL
if (data != NULL) {
  edu = json_object_object_get(data, "education");
  prof= json_object_object_get(data, "profession");
}

if (!name || !sex|| !edu || !prof) {
  printf("parse failed.");
  json_object_put(root);
  exit(-1);
}

// Fetch value
printf("name=%s", json_object_get_string(name));
printf("sex=%d", json_object_get_int(sex));
printf("education=%s", json_object_get_string(edu));
printf("profession=%s", json_object_get_string(prof));

// Free
json_object_put(root);

參考資料
json-c-0.9库的json_object_object_get()引发崩溃问题


1 則留言: