Source Code File 13-06_jsonwrite
13-06_jsonwrite.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 filename[] = "jsontest.json";
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);
json_object_to_file(filename,rootobj);
printf("File %s written\n",filename);
return(0);
}
Output
File jsontest.json written
Notes
* File contents:
{"address":{"street":"123 Main St.","city":"Anytown","state":"WY","zip":"98765"}}
(A single line of output.)
Copyright © 1997-2025 by QPBC.
All rights reserved
