Source Code File 13-05_objectobject

13-05_objectobject.c

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

int main()
{
    json_object *rootobj,*adata,*child;
    const char a_name[] = "address";
    const char s_name[] = "street";
    const char s_value[] = "123 Main St.";
    const char c_name[] = "city";
    const char c_value[] = "Anytown";
    const char t_name[] = "state";
    const char t_value[] = "WY";
    const char z_name[] = "zip";
    const char z_value[] = "98765";
    const char *jstring;

    rootobj = json_object_new_object();
    adata = json_object_new_object();
    if( rootobj==NULL || adata==NULL )
    {
        fprintf(stderr,"Initialization failure\n");
        exit(1);
    }

    /* Create and add child objects */
    child = json_object_new_string(s_value);
    json_object_object_add(adata,s_name,child );
    child = json_object_new_string(c_value);
    json_object_object_add(adata,c_name,child );
    child = json_object_new_string(t_value);
    json_object_object_add(adata,t_name,child );
    child = json_object_new_string(z_value);
    json_object_object_add(adata,z_name,child );
    /* add adata object to root object */
    json_object_object_add(rootobj,a_name,adata);

    jstring = json_object_to_json_string_ext(
            rootobj,
            JSON_C_TO_STRING_PRETTY
            );
    puts(jstring);

    return(0);
}

Output

{
  "address":{
    "street":"123 Main St.",
    "city":"Anytown",
    "state":"WY",
    "zip":"98765"
  }
}

Notes

* All those const char strings are created in this code to avoid long statements that would wrap ugly in the book. It's perfectly fine to directly include the strings in the json_object_new_string() and json_object_object_add() functions.