2 Copyright (C) 2006 Georgia Public Library Service
3 Bill Erickson <billserickson@gmail.com>
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
20 #include <opensrf/log.h>
21 #include <opensrf/osrf_json.h>
22 #include <opensrf/osrf_json_utils.h>
23 #include <opensrf/osrf_utf8.h>
25 /* cleans up an object if it is morphing another object, also
26 * verifies that the appropriate storage container exists where appropriate */
27 #define JSON_INIT_CLEAR(_obj_, newtype) \
28 if( _obj_->type == JSON_HASH && newtype != JSON_HASH ) { \
29 osrfHashFree(_obj_->value.h); \
30 _obj_->value.h = NULL; \
31 } else if( _obj_->type == JSON_ARRAY && newtype != JSON_ARRAY ) { \
32 osrfListFree(_obj_->value.l); \
33 _obj_->value.l = NULL; \
34 } else if( _obj_->type == JSON_STRING || _obj_->type == JSON_NUMBER ) { \
35 free(_obj_->value.s); \
36 _obj_->value.s = NULL; \
38 _obj_->type = newtype;\
39 if( newtype == JSON_HASH && _obj_->value.h == NULL ) { \
40 _obj_->value.h = osrfNewHash(); \
41 osrfHashSetCallback( _obj_->value.h, _jsonFreeHashItem ); \
42 } else if( newtype == JSON_ARRAY && _obj_->value.l == NULL ) { \
43 _obj_->value.l = osrfNewList(); \
44 _obj_->value.l->freeItem = _jsonFreeListItem;\
47 static int unusedObjCapture = 0;
48 static int unusedObjRelease = 0;
49 static int mallocObjCreate = 0;
50 static int currentListLen = 0;
54 union unusedObjUnion* next;
57 typedef union unusedObjUnion unusedObj;
59 // We maintain a free list of jsonObjects that are available
60 // for use, in order to reduce the churning through
61 // malloc() and free().
63 static unusedObj* freeObjList = NULL;
65 static void add_json_to_buffer( const jsonObject* obj,
66 growing_buffer * buf, int do_classname, int second_pass );
69 * Return all unused jsonObjects to the heap
72 void jsonObjectFreeUnused( void ) {
75 while( freeObjList ) {
76 temp = freeObjList->next;
82 jsonObject* jsonNewObject(const char* data) {
87 o = (jsonObject*) freeObjList;
88 freeObjList = freeObjList->next;
92 OSRF_MALLOC( o, sizeof(jsonObject) );
101 o->type = JSON_STRING;
102 o->value.s = strdup(data);
111 jsonObject* jsonNewObjectFmt(const char* data, ...) {
116 o = (jsonObject*) freeObjList;
117 freeObjList = freeObjList->next;
121 OSRF_MALLOC( o, sizeof(jsonObject) );
130 VA_LIST_TO_STRING(data);
131 o->type = JSON_STRING;
132 o->value.s = strdup(VA_BUF);
142 jsonObject* jsonNewNumberObject( double num ) {
143 jsonObject* o = jsonNewObject(NULL);
144 o->type = JSON_NUMBER;
145 o->value.s = doubleToString( num );
150 * Creates a new number object from a numeric string
152 jsonObject* jsonNewNumberStringObject( const char* numstr ) {
155 else if( !jsonIsNumeric( numstr ) )
158 jsonObject* o = jsonNewObject(NULL);
159 o->type = JSON_NUMBER;
160 o->value.s = strdup( numstr );
164 jsonObject* jsonNewBoolObject(int val) {
165 jsonObject* o = jsonNewObject(NULL);
171 jsonObject* jsonNewObjectType(int type) {
172 jsonObject* o = jsonNewObject(NULL);
177 void jsonObjectFree( jsonObject* o ) {
179 if(!o || o->parent) return;
183 case JSON_HASH : osrfHashFree(o->value.h); break;
184 case JSON_ARRAY : osrfListFree(o->value.l); break;
185 case JSON_STRING : free(o->value.s); break;
186 case JSON_NUMBER : free(o->value.s); break;
189 // Stick the old jsonObject onto a free list
190 // for potential reuse
192 unusedObj* unused = (unusedObj*) o;
193 unused->next = freeObjList;
194 freeObjList = unused;
198 if (unusedObjCapture > 1 && !(unusedObjCapture % 1000))
199 osrfLogDebug( OSRF_LOG_MARK, "Objects malloc()'d: %d, "
200 "Reusable objects captured: %d, Objects reused: %d, "
201 "Current List Length: %d",
202 mallocObjCreate, unusedObjCapture, unusedObjRelease, currentListLen );
205 static void _jsonFreeHashItem(char* key, void* item){
207 jsonObject* o = (jsonObject*) item;
208 o->parent = NULL; /* detach the item */
211 static void _jsonFreeListItem(void* item){
213 jsonObject* o = (jsonObject*) item;
214 o->parent = NULL; /* detach the item */
218 void jsonSetBool(jsonObject* bl, int val) {
220 JSON_INIT_CLEAR(bl, JSON_BOOL);
224 unsigned long jsonObjectPush(jsonObject* o, jsonObject* newo) {
226 if(!newo) newo = jsonNewObject(NULL);
227 JSON_INIT_CLEAR(o, JSON_ARRAY);
229 osrfListPush( o->value.l, newo );
230 o->size = o->value.l->size;
234 unsigned long jsonObjectSetIndex(jsonObject* dest, unsigned long index, jsonObject* newObj) {
236 if(!newObj) newObj = jsonNewObject(NULL);
237 JSON_INIT_CLEAR(dest, JSON_ARRAY);
238 newObj->parent = dest;
239 osrfListSet( dest->value.l, newObj, index );
240 dest->size = dest->value.l->size;
241 return dest->value.l->size;
244 unsigned long jsonObjectSetKey( jsonObject* o, const char* key, jsonObject* newo) {
246 if(!newo) newo = jsonNewObject(NULL);
247 JSON_INIT_CLEAR(o, JSON_HASH);
249 osrfHashSet( o->value.h, newo, key );
250 o->size = osrfHashGetCount(o->value.h);
254 jsonObject* jsonObjectGetKey( jsonObject* obj, const char* key ) {
255 if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
256 return osrfHashGet( obj->value.h, key);
259 const jsonObject* jsonObjectGetKeyConst( const jsonObject* obj, const char* key ) {
260 if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
261 return osrfHashGet( obj->value.h, key);
265 * Recursively traverse a jsonObject, formatting it into a JSON string.
267 * The last two parameters are booleans.
269 * If do_classname is true, examine each node for a classname, and if you
270 * find one, pretend that the node is under an extra layer of JSON_HASH, with
271 * JSON_CLASS_KEY and JSON_DATA_KEY as keys.
273 * second_pass should always be false except for some recursive calls. It
274 * is used when expanding classnames, to distinguish between the first and
275 * second passes through a given node.
279 static void add_json_to_buffer( const jsonObject* obj,
280 growing_buffer * buf, int do_classname, int second_pass ) {
283 OSRF_BUFFER_ADD(buf, "null");
287 if( obj->classname && do_classname )
293 // Pretend we see an extra layer of JSON_HASH
295 OSRF_BUFFER_ADD( buf, "{\"" );
296 OSRF_BUFFER_ADD( buf, JSON_CLASS_KEY );
297 OSRF_BUFFER_ADD( buf, "\":\"" );
298 OSRF_BUFFER_ADD( buf, obj->classname );
299 OSRF_BUFFER_ADD( buf, "\",\"" );
300 OSRF_BUFFER_ADD( buf, JSON_DATA_KEY );
301 OSRF_BUFFER_ADD( buf, "\":" );
302 add_json_to_buffer( obj, buf, 1, 1 );
303 buffer_add_char( buf, '}' );
311 if(obj->value.b) OSRF_BUFFER_ADD(buf, "true");
312 else OSRF_BUFFER_ADD(buf, "false");
316 if(obj->value.s) OSRF_BUFFER_ADD( buf, obj->value.s );
317 else OSRF_BUFFER_ADD_CHAR( buf, '0' );
322 OSRF_BUFFER_ADD(buf, "null");
326 OSRF_BUFFER_ADD_CHAR(buf, '"');
327 buffer_append_utf8(buf, obj->value.s);
328 OSRF_BUFFER_ADD_CHAR(buf, '"');
332 OSRF_BUFFER_ADD_CHAR(buf, '[');
335 for( i = 0; i != obj->value.l->size; i++ ) {
336 if(i > 0) OSRF_BUFFER_ADD(buf, ",");
338 OSRF_LIST_GET_INDEX(obj->value.l, i), buf, do_classname, second_pass );
341 OSRF_BUFFER_ADD_CHAR(buf, ']');
347 OSRF_BUFFER_ADD_CHAR(buf, '{');
348 osrfHashIterator* itr = osrfNewHashIterator(obj->value.h);
352 while( (item = osrfHashIteratorNext(itr)) ) {
353 if(i++ > 0) OSRF_BUFFER_ADD_CHAR(buf, ',');
354 OSRF_BUFFER_ADD_CHAR(buf, '"');
355 buffer_append_utf8(buf, osrfHashIteratorKey(itr));
356 OSRF_BUFFER_ADD(buf, "\":");
357 add_json_to_buffer( item, buf, do_classname, second_pass );
360 osrfHashIteratorFree(itr);
361 OSRF_BUFFER_ADD_CHAR(buf, '}');
367 char* jsonObjectToJSONRaw( const jsonObject* obj ) {
368 if(!obj) return NULL;
369 growing_buffer* buf = buffer_init(32);
370 add_json_to_buffer( obj, buf, 0, 0 );
371 return buffer_release( buf );
374 char* jsonObjectToJSON( const jsonObject* obj ) {
375 if(!obj) return NULL;
376 growing_buffer* buf = buffer_init(32);
377 add_json_to_buffer( obj, buf, 1, 0 );
378 return buffer_release( buf );
381 jsonIterator* jsonNewIterator(const jsonObject* obj) {
382 if(!obj) return NULL;
384 OSRF_MALLOC(itr, sizeof(jsonIterator));
386 itr->obj = (jsonObject*) obj;
390 if( obj->type == JSON_HASH )
391 itr->hashItr = osrfNewHashIterator(obj->value.h);
398 void jsonIteratorFree(jsonIterator* itr) {
401 osrfHashIteratorFree(itr->hashItr);
405 jsonObject* jsonIteratorNext(jsonIterator* itr) {
406 if(!(itr && itr->obj)) return NULL;
407 if( itr->obj->type == JSON_HASH ) {
408 if(!itr->hashItr) return NULL;
409 jsonObject* item = osrfHashIteratorNext(itr->hashItr);
410 if(!item) return NULL;
412 itr->key = strdup( osrfHashIteratorKey(itr->hashItr) );
415 return jsonObjectGetIndex( itr->obj, itr->index++ );
419 int jsonIteratorHasNext(const jsonIterator* itr) {
420 if(!(itr && itr->obj)) return 0;
421 if( itr->obj->type == JSON_HASH )
422 return osrfHashIteratorHasNext( itr->hashItr );
423 return (itr->index < itr->obj->size) ? 1 : 0;
426 jsonObject* jsonObjectGetIndex( const jsonObject* obj, unsigned long index ) {
427 if(!obj) return NULL;
428 return (obj->type == JSON_ARRAY) ?
429 (OSRF_LIST_GET_INDEX(obj->value.l, index)) : NULL;
434 unsigned long jsonObjectRemoveIndex(jsonObject* dest, unsigned long index) {
435 if( dest && dest->type == JSON_ARRAY ) {
436 osrfListRemove(dest->value.l, index);
437 return dest->value.l->size;
443 jsonObject* jsonObjectExtractIndex(jsonObject* dest, unsigned long index) {
444 if( dest && dest->type == JSON_ARRAY ) {
445 return osrfListExtract(dest->value.l, index);
451 unsigned long jsonObjectRemoveKey( jsonObject* dest, const char* key) {
452 if( dest && key && dest->type == JSON_HASH ) {
453 osrfHashRemove(dest->value.h, key);
460 Allocate a buffer and format a specified numeric value into it.
461 Caller is responsible for freeing the buffer.
463 char* doubleToString( double num ) {
466 size_t len = snprintf(buf, sizeof( buf ), "%.30g", num) + 1;
467 if( len < sizeof( buf ) )
468 return strdup( buf );
471 // Need a bigger buffer (should never be necessary)
473 char* bigger_buff = safe_malloc( len + 1 );
474 (void) snprintf(bigger_buff, len + 1, "%.30g", num);
479 char* jsonObjectGetString(const jsonObject* obj) {
482 if( obj->type == JSON_STRING )
484 else if( obj->type == JSON_NUMBER )
485 return obj->value.s ? obj->value.s : "0";
493 double jsonObjectGetNumber( const jsonObject* obj ) {
494 return (obj && obj->type == JSON_NUMBER && obj->value.s)
495 ? strtod( obj->value.s, NULL ) : 0;
498 void jsonObjectSetString(jsonObject* dest, const char* string) {
499 if(!(dest && string)) return;
500 JSON_INIT_CLEAR(dest, JSON_STRING);
501 dest->value.s = strdup(string);
505 Turn a jsonObject into a JSON_NUMBER (if it isn't already one) and store
506 a specified numeric string in it. If the string is not numeric,
507 store the equivalent of zero, and return an error status.
509 int jsonObjectSetNumberString(jsonObject* dest, const char* string) {
510 if(!(dest && string)) return -1;
511 JSON_INIT_CLEAR(dest, JSON_NUMBER);
513 if( jsonIsNumeric( string ) ) {
514 dest->value.s = strdup(string);
518 dest->value.s = NULL; // equivalent to zero
523 void jsonObjectSetNumber(jsonObject* dest, double num) {
525 JSON_INIT_CLEAR(dest, JSON_NUMBER);
526 dest->value.s = doubleToString( num );
529 void jsonObjectSetClass(jsonObject* dest, const char* classname ) {
530 if(!(dest && classname)) return;
531 free(dest->classname);
532 dest->classname = strdup(classname);
534 const char* jsonObjectGetClass(const jsonObject* dest) {
535 if(!dest) return NULL;
536 return dest->classname;
539 jsonObject* jsonObjectClone( const jsonObject* o ) {
540 if(!o) return jsonNewObject(NULL);
547 jsonObject* result = NULL;
551 result = jsonNewObject(NULL);
554 result = jsonNewObject(jsonObjectGetString(o));
557 result = jsonNewObject( o->value.s );
558 result->type = JSON_NUMBER;
561 result = jsonNewBoolObject(jsonBoolIsTrue((jsonObject*) o));
564 arr = jsonNewObject(NULL);
565 arr->type = JSON_ARRAY;
566 for(i=0; i < o->size; i++)
567 jsonObjectPush(arr, jsonObjectClone(jsonObjectGetIndex(o, i)));
571 hash = jsonNewObject(NULL);
572 hash->type = JSON_HASH;
573 itr = jsonNewIterator(o);
574 while( (tmp = jsonIteratorNext(itr)) )
575 jsonObjectSetKey(hash, itr->key, jsonObjectClone(tmp));
576 jsonIteratorFree(itr);
581 jsonObjectSetClass(result, jsonObjectGetClass(o));
585 int jsonBoolIsTrue( const jsonObject* boolObj ) {
586 if( boolObj && boolObj->type == JSON_BOOL && boolObj->value.b )
592 char* jsonObjectToSimpleString( const jsonObject* o ) {
600 value = strdup( o->value.s ? o->value.s : "0" );
604 value = strdup(o->value.s);
611 Return 1 if the string is numeric, otherwise return 0.
612 This validation follows the rules defined by the grammar at:
615 int jsonIsNumeric( const char* s ) {
617 if( !s || !*s ) return 0;
621 // skip leading minus sign, if present (leading plus sign not allowed)
626 // There must be at least one digit to the left of the decimal
628 if( isdigit( (unsigned char) *p ) ) {
631 // If the first digit is zero, it must be the
632 // only digit to the lerft of the decimal
634 if( isdigit( (unsigned char) *p ) )
639 // Skip oer the following digits
641 while( isdigit( (unsigned char) *p ) ) ++p;
654 // If there is a decimal point, there must be
655 // at least one digit to the right of it
657 if( isdigit( (unsigned char) *p ) )
662 // skip over contiguous digits
664 while( isdigit( (unsigned char) *p ) ) ++p;
668 return 1; // decimal fraction, no exponent
669 else if( *p != 'e' && *p != 'E' )
670 return 0; // extra junk, no exponent
674 // If we get this far, we have the beginnings of an exponent.
675 // Skip over optional sign of exponent.
677 if( '-' == *p || '+' == *p )
680 // There must be at least one digit in the exponent
682 if( isdigit( (unsigned char) *p ) )
687 // skip over contiguous digits
689 while( isdigit( (unsigned char) *p ) ) ++p;
692 return 0; // extra junk
694 return 1; // number with exponent
698 Allocate and reformat a numeric string into one that is valid
699 by JSON rules. If the string is not numeric, return NULL.
700 Caller is responsible for freeing the buffer.
702 char* jsonScrubNumber( const char* s ) {
703 if( !s || !*s ) return NULL;
705 growing_buffer* buf = buffer_init( 64 );
707 // Skip leading white space, if present
709 while( isspace( (unsigned char) *s ) ) ++s;
711 // Skip leading plus sign, if present, but keep a minus
715 buffer_add_char( buf, '-' );
727 // Skip any leading zeros
729 while( '0' == *s ) ++s;
731 // Capture digits to the left of the decimal,
732 // and note whether there are any.
734 int left_digit = 0; // boolean
736 if( isdigit( (unsigned char) *s ) ) {
737 buffer_add_char( buf, *s++ );
741 while( isdigit( (unsigned char) *s ) )
742 buffer_add_char( buf, *s++ );
744 // Now we expect to see a decimal point,
745 // an exponent, or end-of-string.
753 // Add a single leading zero, if we need to
756 buffer_add_char( buf, '0' );
757 buffer_add_char( buf, '.' );
760 if( ! left_digit && ! isdigit( (unsigned char) *s ) )
762 // No digits on either side of decimal
768 // Collect digits to right of decimal
770 while( isdigit( (unsigned char) *s ) )
771 buffer_add_char( buf, *s++ );
778 // Exponent; we'll deal with it later, but
779 // meanwhile make sure we have something
783 buffer_add_char( buf, '1' );
787 // Unexpected character; bail out
793 if( '\0' == *s ) // Are we done yet?
794 return buffer_release( buf );
796 if( 'e' != *s && 'E' != *s ) {
798 // Unexpected character: bail out
804 // We have an exponent. Load the e or E,
805 // and the sign if there is one.
807 buffer_add_char( buf, *s++ );
809 if( '+' == *s || '-' == *s )
810 buffer_add_char( buf, *s++ );
812 // Collect digits of the exponent
814 while( isdigit( (unsigned char) *s ) )
815 buffer_add_char( buf, *s++ );
817 // There better not be anything left
824 return buffer_release( buf );