Source Code File 12-05_arrays
12-05_arrays.c
#include <stdio.h>
#include <stdlib.h>
#include <json-c/json.h>
int main()
{
const char filename[] = "sample.json";
json_object *jdata,*keyname,*jelement;
enum json_type type;
struct lh_entry *entry;
char *key;
const char *jstring;
int jint,jbool,elements,x;
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, &keyname);
printf("'%s' type is ",key);
type = json_object_get_type(val);
switch(type)
{
case json_type_array:
elements = json_object_array_length(keyname);
printf("an array with %d elements:",elements);
for( x=0; x<elements; x++)
{
jelement=json_object_array_get_idx(
keyname,
x
);
printf(" %d",json_object_get_int(jelement));
}
putchar('\n');
break;
case json_type_boolean:
jbool = json_object_get_boolean(keyname);
printf("boolean, value: %s\n",
(jbool?"TRUE":"FALSE")
);
break;
case json_type_double:
jdouble = json_object_get_double(keyname);
printf("double, value: %f\n", jdouble);
break;
case json_type_int:
jint = json_object_get_int(keyname);
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(keyname);
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 with 2 elements: 0 0
'assistant' type is string, value: Cad Lackey
'spouse' type is null, value: NULL
'favorite numbers' type is an array with 4 elements: 2 13 23 66
Copyright © 1997-2025 by QPBC.
All rights reserved
