2022年5月2日 星期一

[C] JSON Library

安裝JSON函式庫(操作環境 ubuntu)
sudo apt install libjson-c-dev


範例1
int main()
{
	json_object *retObj_1 = NULL, *retObj_2 = NULL, *json_obj = NULL;
	int val_1, val_2;

	json_obj = json_object_new_object();

	/*Add object*/
	json_object_object_add(json_obj, "item1", json_object_new_int(123));
	json_object_object_add(json_obj, "item2", json_object_new_int(456));

	/*讀出json_obj內的所有key and value*/
	printf("%s\n", json_object_to_json_string(json_obj)); 
	//-> { "item1": 123, "item2": 456 }

	/*Get object, 下列兩種取到的object是一樣的*/
	retObj_1 = json_object_object_get(json_obj, "item1"); 	
	json_object_object_get_ex(json_obj, "item1", &retObj_2);
	//if retObj_1 = 0, item1 isn't existing

	val_1 = json_object_get_int (retObj_1);
	val_2 = json_object_get_int (retObj_2);
	printf(%d\n", json_object_get_int(val_1)); //-> 123
	printf("%d\n", json_object_get_int(val_2)); //-> 123
}


範例2
void json_parse(json_object *jobj) 
{
    int i, arraylen;
    enum json_type type;

    json_object_object_foreach(jobj, key, val) 
    {
        type = json_object_get_type(val);
        printf("type: %d\n", type); 
        //-> type: 3, type: 6, type: 5

        switch (type) 
        {
            case json_type_array: 
                printf("\ntype: json_type_array \n");
                jobj = json_object_object_get(jobj, key);

                printf("array content: %s\n", json_object_to_json_string(jobj)); 
                //-> array length: 3 array content: [ "aaa", "bbb", "ccc" ]

                arraylen = json_object_array_length(jobj);
                printf("array length: %d\n\n",arraylen); 
                //-> array length: 3

                json_object *jvalue;
                for (i = 0; i < arraylen; i ++)
                {
                    jvalue = json_object_array_get_idx(jobj, i);
                    printf("value[%d]: %s\n", i, json_object_get_string(jvalue));
                    //-> array length: 3 value[0]: aaa, value[1]: bbb, value[2]: ccc
                }
                break;
        }
    }
}

int main() 
{
    char * string = "{ \"val_1\": 123, \"val_2\": \"456\",\"val_3\": [ \"aaa\", \"bbb\", \"ccc\"] }";
    json_object * jobj = json_tokener_parse(string);
    json_parse(jobj);
}


others example:
object複製到(把oldObj的X1放到newObj的X2)
#define JSON_OBJ_COPY(json_object) json_tokener_parse(json_object_to_json_string(json_object))
json_object_object_add(newObj, "X2", JSON_OBJ_COPY(json_object_object_get(oldObj, "X1")));



JSON Library Manual

沒有留言:

張貼留言