본문 바로가기

Stupid Computer/2. C 언어

[json/cjson] json_object_is_type 사용법

json_object_is_type is used to check whether the type of the json object is same as that of the specified type. So you can easily guess that the function takes two arguments

#include <json/json.h>
#include <stdio.h>

int main() {
  char * string = "{"sitename" : "joys of programming",
                     "tags" : [ "c" , "c++", "java", "PHP" ],
                     "author-details": { "name" : "Joys of Programming", "Number of Posts" : 10 } 
                     }";
  json_object * jobj = json_tokener_parse(string);
  enum json_type type;
  json_object_object_foreach(jobj, key, val) {
    printf("type: ",type);
    if (json_object_is_type(val, json_type_null)) {
     printf("json_type_nulln");
    }
    if (json_object_is_type(val, json_type_boolean)) {
     printf("json_type_booleann");
    }
    if (json_object_is_type(val, json_type_double)) {
     printf("json_type_doublen");
    }
    if (json_object_is_type(val, json_type_int)) {
     printf("json_type_intn");
    }
    if (json_object_is_type(val, json_type_object)) {
     printf("json_type_objectn");
    }
    if (json_object_is_type(val, json_type_array)) {
     printf("json_type_arrayn");
    }
    if (json_object_is_type(val, json_type_string)) {
     printf("json_type_stringn");
    }
  }
}

The output of the program is something like this

type: json_type_string
type: json_type_array
type: json_type_object

The input to the program is

{
    "sitename" : "joys of programming",
    "tags" : [
        "c" ,
        "c++",
        "java",
        "PHP"
    ],
    "author-details": {
        "name" : "Joys of Programming",
        "Number of Posts" : 10
    }
}


static void checktype(struct json_object *new_obj, const char *field)
{
struct json_object *o = field ? json_object_object_get(new_obj, field) : new_obj;
printf("new_obj%s%-18s: %d,%d,%d,%d,%d,%d,%d\n",
field ? "." : " ", field ? field : "",
json_object_is_type(o, json_type_null),
json_object_is_type(o, json_type_boolean),
json_object_is_type(o, json_type_double),
json_object_is_type(o, json_type_int),
json_object_is_type(o, json_type_object),
json_object_is_type(o, json_type_array),
json_object_is_type(o, json_type_string));
}


이런식으로 쓴다.

json_object_is_type("변수", 데이터형) 결과는 참이면 1, 아니면 0 이렇게 나오는듯하다.
if( ~ ) 속에 넣어서 썼다.