Source Code File 12-02_objects

12-02_objects.c

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

int main()
{
    const char filename[] = "sample.json";
    json_object *jdata;
    enum json_type type;
    struct lh_entry *entry;
    char *key;
    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;
        printf("'%s' type is ",key);
        type = json_object_get_type(val);
        switch(type)
        {
            case json_type_array:
                puts("array");
                break;
            case json_type_boolean:
                puts("boolean");
                break;
            case json_type_double:
                puts("double");
                break;
            case json_type_int:
                puts("integer");
                break;
            case json_type_null:
                puts("null");
                break;
            case json_type_object:
                puts("object");
                break;
            case json_type_string:
                puts("string");
                break;
            default:
                puts("unrecognized");
        }
        entry = entry->next;
    }

    return(0);
}

Output

'firstName' type is string
'middleName' type is string
'lastName' type is string
'address' type is object
'isCartoon' type is boolean
'IQ' type is double
'phones' type is array
'assistant' type is string
'spouse' type is null
'favorite numbers' type is array