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@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
27extern "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
64extern const char *json_number_chars;
65extern const char *json_hex_chars;
66
67/* CAW: added for ANSI C iteration correctness */
68struct json_object_iter
69{
70	char *key;
71	struct json_object *val;
72	struct lh_entry *entry;
73};
74
75/* forward structure definitions */
76
77typedef int json_bool;
78typedef struct printbuf printbuf;
79typedef struct lh_table lh_table;
80typedef struct array_list array_list;
81typedef struct json_object json_object;
82typedef struct json_object_iter json_object_iter;
83typedef struct json_tokener json_tokener;
84
85/**
86 * Type of custom user delete functions.  See json_object_set_serializer.
87 */
88typedef 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 */
93typedef 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
100typedef 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 */
119extern 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 */
129int 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 */
143extern 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 */
159extern 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 * @param obj the json_object instance
165 * @returns a string in JSON format
166 */
167extern const char* json_object_to_json_string(struct json_object *obj);
168
169/** Stringify object to json format
170 * @param obj the json_object instance
171 * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
172 * @returns a string in JSON format
173 */
174extern const char* json_object_to_json_string_ext(struct json_object *obj, int
175flags);
176
177/**
178 * Set a custom serialization function to be used when this particular object
179 * is converted to a string by json_object_to_json_string.
180 *
181 * If a custom serializer is already set on this object, any existing
182 * user_delete function is called before the new one is set.
183 *
184 * If to_string_func is NULL, the other parameters are ignored
185 * and the default behaviour is reset.
186 *
187 * The userdata parameter is optional and may be passed as NULL.  If provided,
188 * it is passed to to_string_func as-is.  This parameter may be NULL even
189 * if user_delete is non-NULL.
190 *
191 * The user_delete parameter is optional and may be passed as NULL, even if
192 * the userdata parameter is non-NULL.  It will be called just before the
193 * json_object is deleted, after it's reference count goes to zero
194 * (see json_object_put()).
195 * If this is not provided, it is up to the caller to free the userdata at
196 * an appropriate time. (i.e. after the json_object is deleted)
197 *
198 * @param jso the object to customize
199 * @param to_string_func the custom serialization function
200 * @param userdata an optional opaque cookie
201 * @param user_delete an optional function from freeing userdata
202 */
203extern void json_object_set_serializer(json_object *jso,
204	json_object_to_json_string_fn to_string_func,
205	void *userdata,
206	json_object_delete_fn *user_delete);
207
208/**
209 * Simply call free on the userdata pointer.
210 * Can be used with json_object_set_serializer().
211 *
212 * @param jso unused
213 * @param userdata the pointer that is passed to free().
214 */
215json_object_delete_fn json_object_free_userdata;
216
217/**
218 * Copy the jso->_userdata string over to pb as-is.
219 * Can be used with json_object_set_serializer().
220 *
221 * @param jso The object whose _userdata is used.
222 * @param pb The destination buffer.
223 * @param level Ignored.
224 * @param flags Ignored.
225 */
226json_object_to_json_string_fn json_object_userdata_to_json_string;
227
228
229/* object type methods */
230
231/** Create a new empty object with a reference count of 1.  The caller of
232 * this object initially has sole ownership.  Remember, when using
233 * json_object_object_add or json_object_array_put_idx, ownership will
234 * transfer to the object/array.  Call json_object_get if you want to maintain
235 * shared ownership or also add this object as a child of multiple objects or
236 * arrays.  Any ownerships you acquired but did not transfer must be released
237 * through json_object_put.
238 *
239 * @returns a json_object of type json_type_object
240 */
241extern struct json_object* json_object_new_object(void);
242
243/** Get the hashtable of a json_object of type json_type_object
244 * @param obj the json_object instance
245 * @returns a linkhash
246 */
247extern struct lh_table* json_object_get_object(struct json_object *obj);
248
249/** Get the size of an object in terms of the number of fields it has.
250 * @param obj the json_object whose length to return
251 */
252extern int json_object_object_length(struct json_object* obj);
253
254/** Add an object field to a json_object of type json_type_object
255 *
256 * The reference count will *not* be incremented. This is to make adding
257 * fields to objects in code more compact. If you want to retain a reference
258 * to an added object, independent of the lifetime of obj, you must wrap the
259 * passed object with json_object_get.
260 *
261 * Upon calling this, the ownership of val transfers to obj.  Thus you must
262 * make sure that you do in fact have ownership over this object.  For instance,
263 * json_object_new_object will give you ownership until you transfer it,
264 * whereas json_object_object_get does not.
265 *
266 * @param obj the json_object instance
267 * @param key the object field name (a private copy will be duplicated)
268 * @param val a json_object or NULL member to associate with the given field
269 */
270extern void json_object_object_add(struct json_object* obj, const char *key,
271				   struct json_object *val);
272
273/** Get the json_object associate with a given object field
274 *
275 * *No* reference counts will be changed.  There is no need to manually adjust
276 * reference counts through the json_object_put/json_object_get methods unless
277 * you need to have the child (value) reference maintain a different lifetime
278 * than the owning parent (obj). Ownership of the returned value is retained
279 * by obj (do not do json_object_put unless you have done a json_object_get).
280 * If you delete the value from obj (json_object_object_del) and wish to access
281 * the returned reference afterwards, make sure you have first gotten shared
282 * ownership through json_object_get (& don't forget to do a json_object_put
283 * or transfer ownership to prevent a memory leak).
284 *
285 * @param obj the json_object instance
286 * @param key the object field name
287 * @returns the json_object associated with the given field name
288 * @deprecated Please use json_object_object_get_ex
289 */
290THIS_FUNCTION_IS_DEPRECATED(extern struct json_object* json_object_object_get(struct json_object* obj,
291						  const char *key));
292
293/** Get the json_object associated with a given object field.
294 *
295 * This returns true if the key is found, false in all other cases (including
296 * if obj isn't a json_type_object).
297 *
298 * *No* reference counts will be changed.  There is no need to manually adjust
299 * reference counts through the json_object_put/json_object_get methods unless
300 * you need to have the child (value) reference maintain a different lifetime
301 * than the owning parent (obj).  Ownership of value is retained by obj.
302 *
303 * @param obj the json_object instance
304 * @param key the object field name
305 * @param value a pointer where to store a reference to the json_object
306 *              associated with the given field name.
307 *
308 *              It is safe to pass a NULL value.
309 * @returns whether or not the key exists
310 */
311extern json_bool json_object_object_get_ex(struct json_object* obj,
312						  const char *key,
313                                                  struct json_object **value);
314
315/** Delete the given json_object field
316 *
317 * The reference count will be decremented for the deleted object.  If there
318 * are no more owners of the value represented by this key, then the value is
319 * freed.  Otherwise, the reference to the value will remain in memory.
320 *
321 * @param obj the json_object instance
322 * @param key the object field name
323 */
324extern void json_object_object_del(struct json_object* obj, const char *key);
325
326/**
327 * Iterate through all keys and values of an object.
328 *
329 * Adding keys to the object while iterating is NOT allowed.
330 *
331 * Deleting an existing key, or replacing an existing key with a
332 * new value IS allowed.
333 *
334 * @param obj the json_object instance
335 * @param key the local name for the char* key variable defined in the body
336 * @param val the local name for the json_object* object variable defined in
337 *            the body
338 */
339#if defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L
340
341# define json_object_object_foreach(obj,key,val) \
342	char *key; \
343	struct json_object *val __attribute__((__unused__)); \
344	for(struct lh_entry *entry ## key = json_object_get_object(obj)->head, *entry_next ## key = NULL; \
345		({ if(entry ## key) { \
346			key = (char*)entry ## key->k; \
347			val = (struct json_object*)entry ## key->v; \
348			entry_next ## key = entry ## key->next; \
349		} ; entry ## key; }); \
350		entry ## key = entry_next ## key )
351
352#else /* ANSI C or MSC */
353
354# define json_object_object_foreach(obj,key,val) \
355	char *key;\
356	struct json_object *val; \
357	struct lh_entry *entry ## key; \
358	struct lh_entry *entry_next ## key = NULL; \
359	for(entry ## key = json_object_get_object(obj)->head; \
360		(entry ## key ? ( \
361			key = (char*)entry ## key->k, \
362			val = (struct json_object*)entry ## key->v, \
363			entry_next ## key = entry ## key->next, \
364			entry ## key) : 0); \
365		entry ## key = entry_next ## key)
366
367#endif /* defined(__GNUC__) && !defined(__STRICT_ANSI__) && __STDC_VERSION__ >= 199901L */
368
369/** Iterate through all keys and values of an object (ANSI C Safe)
370 * @param obj the json_object instance
371 * @param iter the object iterator
372 */
373#define json_object_object_foreachC(obj,iter) \
374 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)
375
376/* Array type methods */
377
378/** Create a new empty json_object of type json_type_array
379 * @returns a json_object of type json_type_array
380 */
381extern struct json_object* json_object_new_array(void);
382
383/** Get the arraylist of a json_object of type json_type_array
384 * @param obj the json_object instance
385 * @returns an arraylist
386 */
387extern struct array_list* json_object_get_array(struct json_object *obj);
388
389/** Get the length of a json_object of type json_type_array
390 * @param obj the json_object instance
391 * @returns an int
392 */
393extern int json_object_array_length(struct json_object *obj);
394
395/** Sorts the elements of jso of type json_type_array
396*
397* Pointers to the json_object pointers will be passed as the two arguments
398* to @sort_fn
399*
400* @param obj the json_object instance
401* @param sort_fn a sorting function
402*/
403extern void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *, const void *));
404
405/** Add an element to the end of a json_object of type json_type_array
406 *
407 * The reference count will *not* be incremented. This is to make adding
408 * fields to objects in code more compact. If you want to retain a reference
409 * to an added object you must wrap the passed object with json_object_get
410 *
411 * @param obj the json_object instance
412 * @param val the json_object to be added
413 */
414extern int json_object_array_add(struct json_object *obj,
415				 struct json_object *val);
416
417/** Insert or replace an element at a specified index in an array (a json_object of type json_type_array)
418 *
419 * The reference count will *not* be incremented. This is to make adding
420 * fields to objects in code more compact. If you want to retain a reference
421 * to an added object you must wrap the passed object with json_object_get
422 *
423 * The reference count of a replaced object will be decremented.
424 *
425 * The array size will be automatically be expanded to the size of the
426 * index if the index is larger than the current size.
427 *
428 * @param obj the json_object instance
429 * @param idx the index to insert the element at
430 * @param val the json_object to be added
431 */
432extern int json_object_array_put_idx(struct json_object *obj, int idx,
433				     struct json_object *val);
434
435/** Get the element at specificed index of the array (a json_object of type json_type_array)
436 * @param obj the json_object instance
437 * @param idx the index to get the element at
438 * @returns the json_object at the specified index (or NULL)
439 */
440extern struct json_object* json_object_array_get_idx(struct json_object *obj,
441						     int idx);
442
443/* json_bool type methods */
444
445/** Create a new empty json_object of type json_type_boolean
446 * @param b a json_bool TRUE or FALSE (0 or 1)
447 * @returns a json_object of type json_type_boolean
448 */
449extern struct json_object* json_object_new_boolean(json_bool b);
450
451/** Get the json_bool value of a json_object
452 *
453 * The type is coerced to a json_bool if the passed object is not a json_bool.
454 * integer and double objects will return FALSE if there value is zero
455 * or TRUE otherwise. If the passed object is a string it will return
456 * TRUE if it has a non zero length. If any other object type is passed
457 * TRUE will be returned if the object is not NULL.
458 *
459 * @param obj the json_object instance
460 * @returns a json_bool
461 */
462extern json_bool json_object_get_boolean(struct json_object *obj);
463
464
465/* int type methods */
466
467/** Create a new empty json_object of type json_type_int
468 * Note that values are stored as 64-bit values internally.
469 * To ensure the full range is maintained, use json_object_new_int64 instead.
470 * @param i the integer
471 * @returns a json_object of type json_type_int
472 */
473extern struct json_object* json_object_new_int(int32_t i);
474
475
476/** Create a new empty json_object of type json_type_int
477 * @param i the integer
478 * @returns a json_object of type json_type_int
479 */
480extern struct json_object* json_object_new_int64(int64_t i);
481
482
483/** Get the int value of a json_object
484 *
485 * The type is coerced to a int if the passed object is not a int.
486 * double objects will return their integer conversion. Strings will be
487 * parsed as an integer. If no conversion exists then 0 is returned
488 * and errno is set to EINVAL. null is equivalent to 0 (no error values set)
489 *
490 * Note that integers are stored internally as 64-bit values.
491 * If the value of too big or too small to fit into 32-bit, INT32_MAX or
492 * INT32_MIN are returned, respectively.
493 *
494 * @param obj the json_object instance
495 * @returns an int
496 */
497extern int32_t json_object_get_int(struct json_object *obj);
498
499/** Get the int value of a json_object
500 *
501 * The type is coerced to a int64 if the passed object is not a int64.
502 * double objects will return their int64 conversion. Strings will be
503 * parsed as an int64. If no conversion exists then 0 is returned.
504 *
505 * NOTE: Set errno to 0 directly before a call to this function to determine
506 * whether or not conversion was successful (it does not clear the value for
507 * you).
508 *
509 * @param obj the json_object instance
510 * @returns an int64
511 */
512extern int64_t json_object_get_int64(struct json_object *obj);
513
514
515/* double type methods */
516
517/** Create a new empty json_object of type json_type_double
518 * @param d the double
519 * @returns a json_object of type json_type_double
520 */
521extern struct json_object* json_object_new_double(double d);
522
523/**
524 * Create a new json_object of type json_type_double, using
525 * the exact serialized representation of the value.
526 *
527 * This allows for numbers that would otherwise get displayed
528 * inefficiently (e.g. 12.3 => "12.300000000000001") to be
529 * serialized with the more convenient form.
530 *
531 * Note: this is used by json_tokener_parse_ex() to allow for
532 *   an exact re-serialization of a parsed object.
533 *
534 * An equivalent sequence of calls is:
535 * @code
536 *   jso = json_object_new_double(d);
537 *   json_object_set_serializer(d, json_object_userdata_to_json_string,
538 *       strdup(ds), json_object_free_userdata)
539 * @endcode
540 *
541 * @param d the numeric value of the double.
542 * @param ds the string representation of the double.  This will be copied.
543 */
544extern struct json_object* json_object_new_double_s(double d, const char *ds);
545
546/** Get the double floating point value of a json_object
547 *
548 * The type is coerced to a double if the passed object is not a double.
549 * integer objects will return their double conversion. Strings will be
550 * parsed as a double. If no conversion exists then 0.0 is returned and
551 * errno is set to EINVAL. null is equivalent to 0 (no error values set)
552 *
553 * If the value is too big to fit in a double, then the value is set to
554 * the closest infinity with errno set to ERANGE. If strings cannot be
555 * converted to their double value, then EINVAL is set & NaN is returned.
556 *
557 * Arrays of length 0 are interpreted as 0 (with no error flags set).
558 * Arrays of length 1 are effectively cast to the equivalent object and
559 * converted using the above rules.  All other arrays set the error to
560 * EINVAL & return NaN.
561 *
562 * NOTE: Set errno to 0 directly before a call to this function to
563 * determine whether or not conversion was successful (it does not clear
564 * the value for you).
565 *
566 * @param obj the json_object instance
567 * @returns a double floating point number
568 */
569extern double json_object_get_double(struct json_object *obj);
570
571
572/* string type methods */
573
574/** Create a new empty json_object of type json_type_string
575 *
576 * A copy of the string is made and the memory is managed by the json_object
577 *
578 * @param s the string
579 * @returns a json_object of type json_type_string
580 */
581extern struct json_object* json_object_new_string(const char *s);
582
583extern struct json_object* json_object_new_string_len(const char *s, int len);
584
585/** Get the string value of a json_object
586 *
587 * If the passed object is not of type json_type_string then the JSON
588 * representation of the object is returned.
589 *
590 * The returned string memory is managed by the json_object and will
591 * be freed when the reference count of the json_object drops to zero.
592 *
593 * @param obj the json_object instance
594 * @returns a string
595 */
596extern const char* json_object_get_string(struct json_object *obj);
597
598/** Get the string length of a json_object
599 *
600 * If the passed object is not of type json_type_string then zero
601 * will be returned.
602 *
603 * @param obj the json_object instance
604 * @returns int
605 */
606extern int json_object_get_string_len(struct json_object *obj);
607
608#ifdef __cplusplus
609}
610#endif
611
612#endif
613