Source Code File 12-04_datatypes

12-04_datatypes.c

#include <stdio.h>
#include <stdlib.h>
#include <json-c/json.h>

int main()
{
    const char filename[] = "sample.json";
    json_object *jdata,*object;
    enum json_type type;
    struct lh_entry *entry;
    char *key;
    const char *jstring;
    int jint,jbool;
    double jdouble;
    struct json_object *val;

    jdata = json_object_from_file(filename);
    if( jdata==NULL )
    {
        fprintf(stderr,"Unable to process %s\n",filename);
        exit(1);
    }

    entry=json_object_get_object(jdata)->head;
    while(entry)
    {
        key = (char *)entry->k;
        val = (struct json_object *)entry->v;
        json_object_object_get_ex(jdata, key, &object);
        printf("'%s' type is ",key);
        type = json_object_get_type(val);
        switch(type)
        {
            case json_type_array:
                puts("an array");
                break;
            case json_type_boolean:
                jbool = json_object_get_boolean(object);
                printf("boolean, value: %s\n",
                        (jbool?"TRUE":"FALSE")
                      );
                break;
            case json_type_double:
                jdouble = json_object_get_double(object);
                printf("double, value: %f\n", jdouble);
                break;
            case json_type_int:
                jint = json_object_get_int(object);
                printf("integer, value: %d\n",jint);
                break;
            case json_type_null:
                printf("null, value: NULL\n");
                break;
            case json_type_object:
                puts("an object");
                break;
            case json_type_string:
                jstring = json_object_get_string(object);
                printf("string, value: %s\n",jstring);
                break;
            default:
                puts("Unrecognized");
        }
        entry=entry->next;
    }

    return(0);
}

Output

'firstName' type is string, value: Simon
'middleName' type is string, value: Bar
'lastName' type is string, value: Sinister
'address' type is an object
'isCartoon' type is boolean, value: TRUE
'IQ' type is double, value: 213.500000
'phones' type is an array
'assistant' type is string, value: Cad Lackey
'spouse' type is null, value: NULL
'favorite numbers' type is an array

Notes

* This code doesn't process nested objects or arrays.