Home | History | Annotate | Download | only in json-c
      1 /*
      2  * $Id: json_object.h,v 1.12 2006/01/30 23:07:57 mclark Exp $
      3  *
      4  * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
      5  * Michael Clark <michael (at) metaparadigm.com>
      6  * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
      7  *
      8  * This library is free software; you can redistribute it and/or modify
      9  * it under the terms of the MIT license. See COPYING for details.
     10  *
     11  */
     12 
     13 #ifndef _json_object_h_
     14 #define _json_object_h_
     15 
     16 #ifdef __GNUC__
     17 #define THIS_FUNCTION_IS_DEPRECATED(func) func __attribute__ ((deprecated))
     18 #elif defined(_MSC_VER)
     19 #define THIS_FUNCTION_IS_DEPRECATED(func) __declspec(deprecated) func
     20 #else
     21 #define THIS_FUNCTION_IS_DEPRECATED(func) func
     22 #endif
     23 
     24 #include "json_inttypes.h"
     25 
     26 #ifdef __cplusplus
     27 extern "C" {
     28 #endif
     29 
     30 #define JSON_OBJECT_DEF_HASH_ENTRIES 16
     31 
     32 /**
     33  * A flag for the json_object_to_json_string_ext() and
     34  * json_object_to_file_ext() functions which causes the output
     35  * to have no extra whitespace or formatting applied.
     36  */
     37 #define JSON_C_TO_STRING_PLAIN      0
     38 /**
     39  * A flag for the json_object_to_json_string_ext() and
     40  * json_object_to_file_ext() functions which causes the output to have
     41  * minimal whitespace inserted to make things slightly more readable.
     42  */
     43 #define JSON_C_TO_STRING_SPACED     (1<<0)
     44 /**
     45  * A flag for the json_object_to_json_string_ext() and
     46  * json_object_to_file_ext() functions which causes
     47  * the output to be formatted.
     48  *
     49  * See the "Two Space Tab" option at http://jsonformatter.curiousconcept.com/
     50  * for an example of the format.
     51  */
     52 #define JSON_C_TO_STRING_PRETTY     (1<<1)
     53 /**
     54  * A flag to drop trailing zero for float values
     55  */
     56 #define JSON_C_TO_STRING_NOZERO     (1<<2)
     57 
     58 #undef FALSE
     59 #define FALSE ((json_bool)0)
     60 
     61 #undef TRUE
     62 #define TRUE ((json_bool)1)
     63 
     64 extern const char *json_number_chars;
     65 extern const char *json_hex_chars;
     66 
     67 /* CAW: added for ANSI C iteration correctness */
     68 struct json_object_iter
     69 {
     70 	char *key;
     71 	struct json_object *val;
     72 	struct lh_entry *entry;
     73 };
     74 
     75 /* forward structure definitions */
     76 
     77 typedef int json_bool;
     78 typedef struct printbuf printbuf;
     79 typedef struct lh_table lh_table;
     80 typedef struct array_list array_list;
     81 typedef struct json_object json_object;
     82 typedef struct json_object_iter json_object_iter;
     83 typedef struct json_tokener json_tokener;
     84 
     85 /**
     86  * Type of custom user delete functions.  See json_object_set_serializer.
     87  */
     88 typedef void (json_object_delete_fn)(struct json_object *jso, void *userdata);
     89 
     90 /**
     91  * Type of a custom serialization function.  See json_object_set_serializer.
     92  */
     93 typedef int (json_object_to_json_string_fn)(struct json_object *jso,
     94 						struct printbuf *pb,
     95 						int level,
     96 						int flags);
     97 
     98 /* supported object types */
     99 
    100 typedef enum json_type {
    101   /* If you change this, be sure to update json_type_to_name() too */
    102   json_type_null,
    103   json_type_boolean,
    104   json_type_double,
    105   json_type_int,
    106   json_type_object,
    107   json_type_array,
    108   json_type_string
    109 } json_type;
    110 
    111 /* reference counting functions */
    112 
    113 /**
    114  * Increment the reference count of json_object, thereby grabbing shared
    115  * ownership of obj.
    116  *
    117  * @param obj the json_object instance
    118  */
    119 extern struct json_object* json_object_get(struct json_object *obj);
    120 
    121 /**
    122  * Decrement the reference count of json_object and free if it reaches zero.
    123  * You must have ownership of obj prior to doing this or you will cause an
    124  * imbalance in the reference count.
    125  *
    126  * @param obj the json_object instance
    127  * @returns 1 if the object was freed.
    128  */
    129 int json_object_put(struct json_object *obj);
    130 
    131 /**
    132  * Check if the json_object is of a given type
    133  * @param obj the json_object instance
    134  * @param type one of:
    135      json_type_null (i.e. obj == NULL),
    136      json_type_boolean,
    137      json_type_double,
    138      json_type_int,
    139      json_type_object,
    140      json_type_array,
    141      json_type_string
    142  */
    143 extern int json_object_is_type(struct json_object *obj, enum json_type type);
    144 
    145 /**
    146  * Get the type of the json_object.  See also json_type_to_name() to turn this
    147  * into a string suitable, for instance, for logging.
    148  *
    149  * @param obj the json_object instance
    150  * @returns type being one of:
    151      json_type_null (i.e. obj == NULL),
    152      json_type_boolean,
    153      json_type_double,
    154      json_type_int,
    155      json_type_object,
    156      json_type_array,
    157      json_type_string
    158  */
    159 extern enum json_type json_object_get_type(struct json_object *obj);
    160 
    161 
    162 /** Stringify object to json format.
    163  * Equivalent to json_object_to_json_string_ext(obj, JSON_C_TO_STRING_SPACED)
    164  * The pointer you get is an internal of your json object. You don't
    165  * have to free it, later use of json_object_put() should be sufficient.
    166  * If you can not ensure there's no concurrent access to *obj use
    167  * strdup().
    168  * @param obj the json_object instance
    169  * @returns a string in JSON format
    170  */
    171 extern const char* json_object_to_json_string(struct json_object *obj);
    172 
    173 /** Stringify object to json format
    174  * @see json_object_to_json_string() for details on how to free string.
    175  * @param obj the json_object instance
    176  * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
    177  * @returns a string in JSON format
    178  */
    179 extern const char* json_object_to_json_string_ext(struct json_object *obj, int
    180 flags);
    181 
    182 /**
    183  * Set a custom serialization function to be used when this particular object
    184  * is converted to a string by json_object_to_json_string.
    185  *
    186  * If a custom serializer is already set on this object, any existing
    187  * user_delete function is called before the new one is set.
    188  *
    189  * If to_string_func is NULL, the other parameters are ignored
    190  * and the default behaviour is reset.
    191  *
    192  * The userdata parameter is optional and may be passed as NULL.  If provided,
    193  * it is passed to to_string_func as-is.  This parameter may be NULL even
    194  * if user_delete is non-NULL.
    195  *
    196  * The user_delete parameter is optional and may be passed as NULL, even if
    197  * the userdata parameter is non-NULL.  It will be called just before the
    198  * json_object is deleted, after it's reference count goes to zero
    199  * (see json_object_put()).
    200  * If this is not provided, it is up to the caller to free the userdata at
    201  * an appropriate time. (i.e. after the json_object is deleted)
    202  *
    203  * @param jso the object to customize
    204  * @param to_string_func the custom serialization function
    205  * @param userdata an optional opaque cookie
    206  * @param user_delete an optional function from freeing userdata
    207  */
    208 extern void json_object_set_serializer(json_object *jso,
    209 	json_object_to_json_string_fn to_string_func,
    210 	void *userdata,
    211 	json_object_delete_fn *user_delete);
    212 
    213 /**
    214  * Simply call free on the userdata pointer.
    215  * Can be used with json_object_set_serializer().
    216  *
    217  * @param jso unused
    218  * @param userdata the pointer that is passed to free().
    219  */
    220 json_object_delete_fn json_object_free_userdata;
    221 
    222 /**
    223  * Copy the jso->_userdata string over to pb as-is.
    224  * Can be used with json_object_set_serializer().
    225  *
    226  * @param jso The object whose _userdata is used.
    227  * @param pb The destination buffer.
    228  * @param level Ignored.
    229  * @param flags Ignored.
    230  */
    231 json_object_to_json_string_fn json_object_userdata_to_json_string;
    232 
    233 
    234 /* object type methods */
    235 
    236 /** Create a new empty object with a reference count of 1.  The caller of
    237  * this object initially has sole ownership.  Remember, when using
    238  * json_object_object_add or json_object_array_put_idx, ownership will
    239  * transfer to the object/array.  Call json_object_get if you want to maintain
    240  * shared ownership or also add this object as a child of multiple objects or
    241  * arrays.  Any ownerships you acquired but did not transfer must be released
    242  * through json_object_put.
    243  *
    244  * @returns a json_object of type json_type_object
    245  */
    246 extern struct json_object* json_object_new_object(void);
    247 
    248 /** Get the hashtable of a json_object of type json_type_object
    249  * @param obj the json_object instance
    250  * @returns a linkhash
    251  */
    252 extern struct lh_table* json_object_get_object(struct json_object *obj);
    253 
    254 /** Get the size of an object in terms of the number of fields it has.
    255  * @param obj the json_object whose length to return
    256  */
    257 extern int json_object_object_length(struct json_object* obj);
    258 
    259 /** Add an object field to a json_object of type json_type_object
    260  *
    261  * The reference count will *not* be incremented. This is to make adding
    262  * fields to objects in code more compact. If you want to retain a reference
    263  * to an added object, independent of the lifetime of obj, you must wrap the
    264  * passed object with json_object_get.
    265  *
    266  * Upon calling this, the ownership of val transfers to obj.  Thus you must
    267  * make sure that you do in fact have ownership over this object.  For instance,
    268  * json_object_new_object will give you ownership until you transfer it,
    269  * whereas json_object_object_get does not.
    270  *
    271  * @param obj the json_object instance
    272  * @param key the object field name (a private copy will be duplicated)
    273  * @param val a json_object or NULL member to associate with the given field
    274  */
    275 extern void json_object_object_add(struct json_object* obj, const char *key,
    276 				   struct json_object *val);
    277 
    278 /** Get the json_object associate with a given object field
    279  *
    280  * *No* reference counts will be changed.  There is no need to manually adjust
    281  * reference counts through the json_object_put/json_object_get methods unless
    282  * you need to have the child (value) reference maintain a different lifetime
    283  * than the owning parent (obj). Ownership of the returned value is retained
    284  * by obj (do not do json_object_put unless you have done a json_object_get).
    285  * If you delete the value from obj (json_object_object_del) and wish to access
    286  * the returned reference afterwards, make sure you have first gotten shared
    287  * ownership through json_object_get (& don't forget to do a json_object_put
    288  * or transfer ownership to prevent a memory leak).
    289  *
    290  * @param obj the json_object instance
    291  * @param key the object field name
    292  * @returns the json_object associated with the given field name
    293  * @deprecated Please use json_object_object_get_ex
    294  */
    295 THIS_FUNCTION_IS_DEPRECATED(extern struct json_object* json_object_object_get(struct json_object* obj,
    296 						  const char *key));
    297 
    298 /** Get the json_object associated with a given object field.
    299  *
    300  * This returns true if the key is found, false in all other cases (including
    301  * if obj isn't a json_type_object).
    302  *
    303  * *No* reference counts will be changed.  There is no need to manually adjust
    304  * reference counts through the json_object_put/json_object_get methods unless
    305  * you need to have the child (value) reference maintain a different lifetime
    306  * than the owning parent (obj).  Ownership of value is retained by obj.
    307  *
    308  * @param obj the json_object instance
    309  * @param key the object field name
    310  * @param value a pointer where to store a reference to the json_object
    311  *              associated with the given field name.
    312  *
    313  *              It is safe to pass a NULL value.
    314  * @returns whether or not the key exists
    315  */
    316 extern json_bool json_object_object_get_ex(struct json_object* obj,
    317 						  const char *key,
    318                                                   struct json_object **value);
    319 
    320 /** Delete the given json_object field
    321  *
    322  * The reference count will be decremented for the deleted object.  If there
    323  * are no more owners of the value represented by this key, then the value is
    324  * freed.  Otherwise, the reference to the value will remain in memory.
    325  *
    326  * @param obj the json_object instance
    327  * @param key the object field name
    328  */
    329 extern void json_object_object_del(struct json_object* obj, const char *key);
    330 
    331 /**
    332  * Iterate through all keys and values of an object.
    333  *
    334  * Adding keys to the object while iterating is NOT allowed.
    335  *
    336  * Deleting an existing key, or replacing an existing key with a
    337  * new value IS allowed.
    338  *
    339  * @param obj the json_object instance
    340  * @param key the local name for the char* key variable defined in the body
    341  * @param val the local name for the json_object* object variable defined in
    342  *            the body
    343  */
    344 #if defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L
    345 
    346 # define json_object_object_foreach(obj,key,val) \
    347 	char *key; \
    348 	struct json_object *val __attribute__((__unused__)); \
    349 	for(struct lh_entry *entry ## key = json_object_get_object(obj)->head, *entry_next ## key = NULL; \
    350 		({ if(entry ## key) { \
    351 			key = (char*)entry ## key->k; \
    352 			val = (struct json_object*)entry ## key->v; \
    353 			entry_next ## key = entry ## key->next; \
    354 		} ; entry ## key; }); \
    355 		entry ## key = entry_next ## key )
    356 
    357 #else /* ANSI C or MSC */
    358 
    359 # define json_object_object_foreach(obj,key,val) \
    360 	char *key;\
    361 	struct json_object *val; \
    362 	struct lh_entry *entry ## key; \
    363 	struct lh_entry *entry_next ## key = NULL; \
    364 	for(entry ## key = json_object_get_object(obj)->head; \
    365 		(entry ## key ? ( \
    366 			key = (char*)entry ## key->k, \
    367 			val = (struct json_object*)entry ## key->v, \
    368 			entry_next ## key = entry ## key->next, \
    369 			entry ## key) : 0); \
    370 		entry ## key = entry_next ## key)
    371 
    372 #endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L */
    373 
    374 /** Iterate through all keys and values of an object (ANSI C Safe)
    375  * @param obj the json_object instance
    376  * @param iter the object iterator
    377  */
    378 #define json_object_object_foreachC(obj,iter) \
    379  for(iter.entry = json_object_get_object(obj)->head; (iter.entry ? (iter.key = (char*)iter.entry->k, iter.val = (struct json_object*)iter.entry->v, iter.entry) : 0); iter.entry = iter.entry->next)
    380 
    381 /* Array type methods */
    382 
    383 /** Create a new empty json_object of type json_type_array
    384  * @returns a json_object of type json_type_array
    385  */
    386 extern struct json_object* json_object_new_array(void);
    387 
    388 /** Get the arraylist of a json_object of type json_type_array
    389  * @param obj the json_object instance
    390  * @returns an arraylist
    391  */
    392 extern struct array_list* json_object_get_array(struct json_object *obj);
    393 
    394 /** Get the length of a json_object of type json_type_array
    395  * @param obj the json_object instance
    396  * @returns an int
    397  */
    398 extern int json_object_array_length(struct json_object *obj);
    399 
    400 /** Sorts the elements of jso of type json_type_array
    401 *
    402 * Pointers to the json_object pointers will be passed as the two arguments
    403 * to @sort_fn
    404 *
    405 * @param obj the json_object instance
    406 * @param sort_fn a sorting function
    407 */
    408 extern void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *, const void *));
    409 
    410 /** Add an element to the end of a json_object of type json_type_array
    411  *
    412  * The reference count will *not* be incremented. This is to make adding
    413  * fields to objects in code more compact. If you want to retain a reference
    414  * to an added object you must wrap the passed object with json_object_get
    415  *
    416  * @param obj the json_object instance
    417  * @param val the json_object to be added
    418  */
    419 extern int json_object_array_add(struct json_object *obj,
    420 				 struct json_object *val);
    421 
    422 /** Insert or replace an element at a specified index in an array (a json_object of type json_type_array)
    423  *
    424  * The reference count will *not* be incremented. This is to make adding
    425  * fields to objects in code more compact. If you want to retain a reference
    426  * to an added object you must wrap the passed object with json_object_get
    427  *
    428  * The reference count of a replaced object will be decremented.
    429  *
    430  * The array size will be automatically be expanded to the size of the
    431  * index if the index is larger than the current size.
    432  *
    433  * @param obj the json_object instance
    434  * @param idx the index to insert the element at
    435  * @param val the json_object to be added
    436  */
    437 extern int json_object_array_put_idx(struct json_object *obj, int idx,
    438 				     struct json_object *val);
    439 
    440 /** Get the element at specificed index of the array (a json_object of type json_type_array)
    441  * @param obj the json_object instance
    442  * @param idx the index to get the element at
    443  * @returns the json_object at the specified index (or NULL)
    444  */
    445 extern struct json_object* json_object_array_get_idx(struct json_object *obj,
    446 						     int idx);
    447 
    448 /* json_bool type methods */
    449 
    450 /** Create a new empty json_object of type json_type_boolean
    451  * @param b a json_bool TRUE or FALSE (0 or 1)
    452  * @returns a json_object of type json_type_boolean
    453  */
    454 extern struct json_object* json_object_new_boolean(json_bool b);
    455 
    456 /** Get the json_bool value of a json_object
    457  *
    458  * The type is coerced to a json_bool if the passed object is not a json_bool.
    459  * integer and double objects will return FALSE if there value is zero
    460  * or TRUE otherwise. If the passed object is a string it will return
    461  * TRUE if it has a non zero length. If any other object type is passed
    462  * TRUE will be returned if the object is not NULL.
    463  *
    464  * @param obj the json_object instance
    465  * @returns a json_bool
    466  */
    467 extern json_bool json_object_get_boolean(struct json_object *obj);
    468 
    469 
    470 /* int type methods */
    471 
    472 /** Create a new empty json_object of type json_type_int
    473  * Note that values are stored as 64-bit values internally.
    474  * To ensure the full range is maintained, use json_object_new_int64 instead.
    475  * @param i the integer
    476  * @returns a json_object of type json_type_int
    477  */
    478 extern struct json_object* json_object_new_int(int32_t i);
    479 
    480 
    481 /** Create a new empty json_object of type json_type_int
    482  * @param i the integer
    483  * @returns a json_object of type json_type_int
    484  */
    485 extern struct json_object* json_object_new_int64(int64_t i);
    486 
    487 
    488 /** Get the int value of a json_object
    489  *
    490  * The type is coerced to a int if the passed object is not a int.
    491  * double objects will return their integer conversion. Strings will be
    492  * parsed as an integer. If no conversion exists then 0 is returned
    493  * and errno is set to EINVAL. null is equivalent to 0 (no error values set)
    494  *
    495  * Note that integers are stored internally as 64-bit values.
    496  * If the value of too big or too small to fit into 32-bit, INT32_MAX or
    497  * INT32_MIN are returned, respectively.
    498  *
    499  * @param obj the json_object instance
    500  * @returns an int
    501  */
    502 extern int32_t json_object_get_int(struct json_object *obj);
    503 
    504 /** Get the int value of a json_object
    505  *
    506  * The type is coerced to a int64 if the passed object is not a int64.
    507  * double objects will return their int64 conversion. Strings will be
    508  * parsed as an int64. If no conversion exists then 0 is returned.
    509  *
    510  * NOTE: Set errno to 0 directly before a call to this function to determine
    511  * whether or not conversion was successful (it does not clear the value for
    512  * you).
    513  *
    514  * @param obj the json_object instance
    515  * @returns an int64
    516  */
    517 extern int64_t json_object_get_int64(struct json_object *obj);
    518 
    519 
    520 /* double type methods */
    521 
    522 /** Create a new empty json_object of type json_type_double
    523  * @param d the double
    524  * @returns a json_object of type json_type_double
    525  */
    526 extern struct json_object* json_object_new_double(double d);
    527 
    528 /**
    529  * Create a new json_object of type json_type_double, using
    530  * the exact serialized representation of the value.
    531  *
    532  * This allows for numbers that would otherwise get displayed
    533  * inefficiently (e.g. 12.3 => "12.300000000000001") to be
    534  * serialized with the more convenient form.
    535  *
    536  * Note: this is used by json_tokener_parse_ex() to allow for
    537  *   an exact re-serialization of a parsed object.
    538  *
    539  * An equivalent sequence of calls is:
    540  * @code
    541  *   jso = json_object_new_double(d);
    542  *   json_object_set_serializer(d, json_object_userdata_to_json_string,
    543  *       strdup(ds), json_object_free_userdata)
    544  * @endcode
    545  *
    546  * @param d the numeric value of the double.
    547  * @param ds the string representation of the double.  This will be copied.
    548  */
    549 extern struct json_object* json_object_new_double_s(double d, const char *ds);
    550 
    551 /** Get the double floating point value of a json_object
    552  *
    553  * The type is coerced to a double if the passed object is not a double.
    554  * integer objects will return their double conversion. Strings will be
    555  * parsed as a double. If no conversion exists then 0.0 is returned and
    556  * errno is set to EINVAL. null is equivalent to 0 (no error values set)
    557  *
    558  * If the value is too big to fit in a double, then the value is set to
    559  * the closest infinity with errno set to ERANGE. If strings cannot be
    560  * converted to their double value, then EINVAL is set & NaN is returned.
    561  *
    562  * Arrays of length 0 are interpreted as 0 (with no error flags set).
    563  * Arrays of length 1 are effectively cast to the equivalent object and
    564  * converted using the above rules.  All other arrays set the error to
    565  * EINVAL & return NaN.
    566  *
    567  * NOTE: Set errno to 0 directly before a call to this function to
    568  * determine whether or not conversion was successful (it does not clear
    569  * the value for you).
    570  *
    571  * @param obj the json_object instance
    572  * @returns a double floating point number
    573  */
    574 extern double json_object_get_double(struct json_object *obj);
    575 
    576 
    577 /* string type methods */
    578 
    579 /** Create a new empty json_object of type json_type_string
    580  *
    581  * A copy of the string is made and the memory is managed by the json_object
    582  *
    583  * @param s the string
    584  * @returns a json_object of type json_type_string
    585  */
    586 extern struct json_object* json_object_new_string(const char *s);
    587 
    588 extern struct json_object* json_object_new_string_len(const char *s, int len);
    589 
    590 /** Get the string value of a json_object
    591  *
    592  * If the passed object is not of type json_type_string then the JSON
    593  * representation of the object is returned.
    594  *
    595  * The returned string memory is managed by the json_object and will
    596  * be freed when the reference count of the json_object drops to zero.
    597  *
    598  * @param obj the json_object instance
    599  * @returns a string
    600  */
    601 extern const char* json_object_get_string(struct json_object *obj);
    602 
    603 /** Get the string length of a json_object
    604  *
    605  * If the passed object is not of type json_type_string then zero
    606  * will be returned.
    607  *
    608  * @param obj the json_object instance
    609  * @returns int
    610  */
    611 extern int json_object_get_string_len(struct json_object *obj);
    612 
    613 #ifdef __cplusplus
    614 }
    615 #endif
    616 
    617 #endif
    618