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>
24 /* cleans up an object if it is morphing another object, also
25 * verifies that the appropriate storage container exists where appropriate */
26 #define JSON_INIT_CLEAR(_obj_, newtype) \
27 if( _obj_->type == JSON_HASH && newtype != JSON_HASH ) { \
28 osrfHashFree(_obj_->value.h); \
29 _obj_->value.h = NULL; \
30 } else if( _obj_->type == JSON_ARRAY && newtype != JSON_ARRAY ) { \
31 osrfListFree(_obj_->value.l); \
32 _obj_->value.l = NULL; \
33 } else if( _obj_->type == JSON_STRING || _obj_->type == JSON_NUMBER ) { \
34 free(_obj_->value.s); \
35 _obj_->value.s = NULL; \
37 _obj_->type = newtype;\
38 if( newtype == JSON_HASH && _obj_->value.h == NULL ) { \
39 _obj_->value.h = osrfNewHash(); \
40 osrfHashSetCallback( _obj_->value.h, _jsonFreeHashItem ); \
41 } else if( newtype == JSON_ARRAY && _obj_->value.l == NULL ) { \
42 _obj_->value.l = osrfNewList(); \
43 _obj_->value.l->freeItem = _jsonFreeListItem;\
46 static int unusedObjCapture = 0;
47 static int unusedObjRelease = 0;
48 static int mallocObjCreate = 0;
49 static int currentListLen = 0;
53 union unusedObjUnion* next;
56 typedef union unusedObjUnion unusedObj;
58 // We maintain a free list of jsonObjects that are available
59 // for use, in order to reduce the churning through
60 // malloc() and free().
62 static unusedObj* freeObjList = NULL;
64 static void add_json_to_buffer( const jsonObject* obj,
65 growing_buffer * buf, int do_classname, int second_pass );
68 * Return all unused jsonObjects to the heap
71 void jsonObjectFreeUnused( void ) {
74 while( freeObjList ) {
75 temp = freeObjList->next;
81 jsonObject* jsonNewObject(const char* data) {
86 o = (jsonObject*) freeObjList;
87 freeObjList = freeObjList->next;
91 OSRF_MALLOC( o, sizeof(jsonObject) );
100 o->type = JSON_STRING;
101 o->value.s = strdup(data);
110 jsonObject* jsonNewObjectFmt(const char* data, ...) {
115 o = (jsonObject*) freeObjList;
116 freeObjList = freeObjList->next;
120 OSRF_MALLOC( o, sizeof(jsonObject) );
129 VA_LIST_TO_STRING(data);
130 o->type = JSON_STRING;
131 o->value.s = strdup(VA_BUF);
141 jsonObject* jsonNewNumberObject( double num ) {
142 jsonObject* o = jsonNewObject(NULL);
143 o->type = JSON_NUMBER;
144 o->value.s = doubleToString( num );
149 * Creates a new number object from a numeric string
151 jsonObject* jsonNewNumberStringObject( const char* numstr ) {
154 else if( !jsonIsNumeric( numstr ) )
157 jsonObject* o = jsonNewObject(NULL);
158 o->type = JSON_NUMBER;
159 o->value.s = strdup( numstr );
163 jsonObject* jsonNewBoolObject(int val) {
164 jsonObject* o = jsonNewObject(NULL);
170 jsonObject* jsonNewObjectType(int type) {
171 jsonObject* o = jsonNewObject(NULL);
176 void jsonObjectFree( jsonObject* o ) {
178 if(!o || o->parent) return;
182 case JSON_HASH : osrfHashFree(o->value.h); break;
183 case JSON_ARRAY : osrfListFree(o->value.l); break;
184 case JSON_STRING : free(o->value.s); break;
185 case JSON_NUMBER : free(o->value.s); break;
188 // Stick the old jsonObject onto a free list
189 // for potential reuse
191 unusedObj* unused = (unusedObj*) o;
192 unused->next = freeObjList;
193 freeObjList = unused;
197 if (unusedObjCapture > 1 && !(unusedObjCapture % 1000))
198 osrfLogDebug( OSRF_LOG_MARK, "Objects malloc()'d: %d, "
199 "Reusable objects captured: %d, Objects reused: %d, "
200 "Current List Length: %d",
201 mallocObjCreate, unusedObjCapture, unusedObjRelease, currentListLen );
204 static void _jsonFreeHashItem(char* key, void* item){
206 jsonObject* o = (jsonObject*) item;
207 o->parent = NULL; /* detach the item */
210 static void _jsonFreeListItem(void* item){
212 jsonObject* o = (jsonObject*) item;
213 o->parent = NULL; /* detach the item */
217 void jsonSetBool(jsonObject* bl, int val) {
219 JSON_INIT_CLEAR(bl, JSON_BOOL);
223 unsigned long jsonObjectPush(jsonObject* o, jsonObject* newo) {
225 if(!newo) newo = jsonNewObject(NULL);
226 JSON_INIT_CLEAR(o, JSON_ARRAY);
228 osrfListPush( o->value.l, newo );
229 o->size = o->value.l->size;
233 unsigned long jsonObjectSetIndex(jsonObject* dest, unsigned long index, jsonObject* newObj) {
235 if(!newObj) newObj = jsonNewObject(NULL);
236 JSON_INIT_CLEAR(dest, JSON_ARRAY);
237 newObj->parent = dest;
238 osrfListSet( dest->value.l, newObj, index );
239 dest->size = dest->value.l->size;
240 return dest->value.l->size;
243 unsigned long jsonObjectSetKey( jsonObject* o, const char* key, jsonObject* newo) {
245 if(!newo) newo = jsonNewObject(NULL);
246 JSON_INIT_CLEAR(o, JSON_HASH);
248 osrfHashSet( o->value.h, newo, key );
249 o->size = osrfHashGetCount(o->value.h);
253 jsonObject* jsonObjectGetKey( jsonObject* obj, const char* key ) {
254 if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
255 return osrfHashGet( obj->value.h, key);
258 const jsonObject* jsonObjectGetKeyConst( const jsonObject* obj, const char* key ) {
259 if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
260 return osrfHashGet( obj->value.h, key);
264 * Recursively traverse a jsonObject, formatting it into a JSON string.
266 * The last two parameters are booleans.
268 * If do_classname is true, examine each node for a classname, and if you
269 * find one, pretend that the node is under an extra layer of JSON_HASH, with
270 * JSON_CLASS_KEY and JSON_DATA_KEY as keys.
272 * second_pass should always be false except for some recursive calls. It
273 * is used when expanding classnames, to distinguish between the first and
274 * second passes through a given node.
278 static void add_json_to_buffer( const jsonObject* obj,
279 growing_buffer * buf, int do_classname, int second_pass ) {
282 OSRF_BUFFER_ADD(buf, "null");
286 if( obj->classname && do_classname )
292 // Pretend we see an extra layer of JSON_HASH
294 OSRF_BUFFER_ADD( buf, "{\"" );
295 OSRF_BUFFER_ADD( buf, JSON_CLASS_KEY );
296 OSRF_BUFFER_ADD( buf, "\":\"" );
297 OSRF_BUFFER_ADD( buf, obj->classname );
298 OSRF_BUFFER_ADD( buf, "\",\"" );
299 OSRF_BUFFER_ADD( buf, JSON_DATA_KEY );
300 OSRF_BUFFER_ADD( buf, "\":" );
301 add_json_to_buffer( obj, buf, 1, 1 );
302 buffer_add_char( buf, '}' );
310 if(obj->value.b) OSRF_BUFFER_ADD(buf, "true");
311 else OSRF_BUFFER_ADD(buf, "false");
315 if(obj->value.s) OSRF_BUFFER_ADD( buf, obj->value.s );
316 else OSRF_BUFFER_ADD_CHAR( buf, '0' );
321 OSRF_BUFFER_ADD(buf, "null");
325 OSRF_BUFFER_ADD_CHAR(buf, '"');
326 buffer_append_uescape(buf, obj->value.s);
327 OSRF_BUFFER_ADD_CHAR(buf, '"');
331 OSRF_BUFFER_ADD_CHAR(buf, '[');
334 for( i = 0; i != obj->value.l->size; i++ ) {
335 if(i > 0) OSRF_BUFFER_ADD(buf, ",");
337 OSRF_LIST_GET_INDEX(obj->value.l, i), buf, do_classname, second_pass );
340 OSRF_BUFFER_ADD_CHAR(buf, ']');
346 OSRF_BUFFER_ADD_CHAR(buf, '{');
347 osrfHashIterator* itr = osrfNewHashIterator(obj->value.h);
351 while( (item = osrfHashIteratorNext(itr)) ) {
352 if(i++ > 0) OSRF_BUFFER_ADD_CHAR(buf, ',');
353 OSRF_BUFFER_ADD_CHAR(buf, '"');
354 OSRF_BUFFER_ADD(buf, osrfHashIteratorKey(itr));
355 OSRF_BUFFER_ADD(buf, "\":");
356 add_json_to_buffer( item, buf, do_classname, second_pass );
359 osrfHashIteratorFree(itr);
360 OSRF_BUFFER_ADD_CHAR(buf, '}');
366 char* jsonObjectToJSONRaw( const jsonObject* obj ) {
367 if(!obj) return NULL;
368 growing_buffer* buf = buffer_init(32);
369 add_json_to_buffer( obj, buf, 0, 0 );
370 return buffer_release( buf );
373 char* jsonObjectToJSON( const jsonObject* obj ) {
374 if(!obj) return NULL;
375 growing_buffer* buf = buffer_init(32);
376 add_json_to_buffer( obj, buf, 1, 0 );
377 return buffer_release( buf );
380 jsonIterator* jsonNewIterator(const jsonObject* obj) {
381 if(!obj) return NULL;
383 OSRF_MALLOC(itr, sizeof(jsonIterator));
385 itr->obj = (jsonObject*) obj;
389 if( obj->type == JSON_HASH )
390 itr->hashItr = osrfNewHashIterator(obj->value.h);
395 void jsonIteratorFree(jsonIterator* itr) {
398 osrfHashIteratorFree(itr->hashItr);
402 jsonObject* jsonIteratorNext(jsonIterator* itr) {
403 if(!(itr && itr->obj)) return NULL;
404 if( itr->obj->type == JSON_HASH ) {
405 if(!itr->hashItr) return NULL;
406 jsonObject* item = osrfHashIteratorNext(itr->hashItr);
407 if(!item) return NULL;
409 itr->key = strdup( osrfHashIteratorKey(itr->hashItr) );
412 return jsonObjectGetIndex( itr->obj, itr->index++ );
416 int jsonIteratorHasNext(const jsonIterator* itr) {
417 if(!(itr && itr->obj)) return 0;
418 if( itr->obj->type == JSON_HASH )
419 return osrfHashIteratorHasNext( itr->hashItr );
420 return (itr->index < itr->obj->size) ? 1 : 0;
423 jsonObject* jsonObjectGetIndex( const jsonObject* obj, unsigned long index ) {
424 if(!obj) return NULL;
425 return (obj->type == JSON_ARRAY) ?
426 (OSRF_LIST_GET_INDEX(obj->value.l, index)) : NULL;
431 unsigned long jsonObjectRemoveIndex(jsonObject* dest, unsigned long index) {
432 if( dest && dest->type == JSON_ARRAY ) {
433 osrfListRemove(dest->value.l, index);
434 return dest->value.l->size;
440 unsigned long jsonObjectRemoveKey( jsonObject* dest, const char* key) {
441 if( dest && key && dest->type == JSON_HASH ) {
442 osrfHashRemove(dest->value.h, key);
449 Allocate a buffer and format a specified numeric value into it.
450 Caller is responsible for freeing the buffer.
452 char* doubleToString( double num ) {
455 size_t len = snprintf(buf, sizeof( buf ), "%.30g", num) + 1;
456 if( len < sizeof( buf ) )
457 return strdup( buf );
460 // Need a bigger buffer (should never be necessary)
462 char* bigger_buff = safe_malloc( len + 1 );
463 (void) snprintf(bigger_buff, len + 1, "%.30g", num);
468 char* jsonObjectGetString(const jsonObject* obj) {
471 if( obj->type == JSON_STRING )
473 else if( obj->type == JSON_NUMBER )
474 return obj->value.s ? obj->value.s : "0";
482 double jsonObjectGetNumber( const jsonObject* obj ) {
483 return (obj && obj->type == JSON_NUMBER && obj->value.s)
484 ? strtod( obj->value.s, NULL ) : 0;
487 void jsonObjectSetString(jsonObject* dest, const char* string) {
488 if(!(dest && string)) return;
489 JSON_INIT_CLEAR(dest, JSON_STRING);
490 dest->value.s = strdup(string);
494 Turn a jsonObject into a JSON_NUMBER (if it isn't already one) and store
495 a specified numeric string in it. If the string is not numeric,
496 store the equivalent of zero, and return an error status.
498 int jsonObjectSetNumberString(jsonObject* dest, const char* string) {
499 if(!(dest && string)) return -1;
500 JSON_INIT_CLEAR(dest, JSON_NUMBER);
502 if( jsonIsNumeric( string ) ) {
503 dest->value.s = strdup(string);
507 dest->value.s = NULL; // equivalent to zero
512 void jsonObjectSetNumber(jsonObject* dest, double num) {
514 JSON_INIT_CLEAR(dest, JSON_NUMBER);
515 dest->value.s = doubleToString( num );
518 void jsonObjectSetClass(jsonObject* dest, const char* classname ) {
519 if(!(dest && classname)) return;
520 free(dest->classname);
521 dest->classname = strdup(classname);
523 const char* jsonObjectGetClass(const jsonObject* dest) {
524 if(!dest) return NULL;
525 return dest->classname;
528 jsonObject* jsonObjectClone( const jsonObject* o ) {
529 if(!o) return jsonNewObject(NULL);
536 jsonObject* result = NULL;
540 result = jsonNewObject(NULL);
543 result = jsonNewObject(jsonObjectGetString(o));
546 result = jsonNewObject( o->value.s );
547 result->type = JSON_NUMBER;
550 result = jsonNewBoolObject(jsonBoolIsTrue((jsonObject*) o));
553 arr = jsonNewObject(NULL);
554 arr->type = JSON_ARRAY;
555 for(i=0; i < o->size; i++)
556 jsonObjectPush(arr, jsonObjectClone(jsonObjectGetIndex(o, i)));
560 hash = jsonNewObject(NULL);
561 hash->type = JSON_HASH;
562 itr = jsonNewIterator(o);
563 while( (tmp = jsonIteratorNext(itr)) )
564 jsonObjectSetKey(hash, itr->key, jsonObjectClone(tmp));
565 jsonIteratorFree(itr);
570 jsonObjectSetClass(result, jsonObjectGetClass(o));
574 int jsonBoolIsTrue( const jsonObject* boolObj ) {
575 if( boolObj && boolObj->type == JSON_BOOL && boolObj->value.b )
581 char* jsonObjectToSimpleString( const jsonObject* o ) {
589 value = strdup( o->value.s ? o->value.s : "0" );
593 value = strdup(o->value.s);
600 Return 1 if the string is numeric, otherwise return 0.
601 This validation follows the rules defined by the grammar at:
604 int jsonIsNumeric( const char* s ) {
606 if( !s || !*s ) return 0;
610 // skip leading minus sign, if present (leading plus sign not allowed)
615 // There must be at least one digit to the left of the decimal
617 if( isdigit( (unsigned char) *p ) ) {
620 // If the first digit is zero, it must be the
621 // only digit to the lerft of the decimal
623 if( isdigit( (unsigned char) *p ) )
628 // Skip oer the following digits
630 while( isdigit( (unsigned char) *p ) ) ++p;
643 // If there is a decimal point, there must be
644 // at least one digit to the right of it
646 if( isdigit( (unsigned char) *p ) )
651 // skip over contiguous digits
653 while( isdigit( (unsigned char) *p ) ) ++p;
657 return 1; // decimal fraction, no exponent
658 else if( *p != 'e' && *p != 'E' )
659 return 0; // extra junk, no exponent
663 // If we get this far, we have the beginnings of an exponent.
664 // Skip over optional sign of exponent.
666 if( '-' == *p || '+' == *p )
669 // There must be at least one digit in the exponent
671 if( isdigit( (unsigned char) *p ) )
676 // skip over contiguous digits
678 while( isdigit( (unsigned char) *p ) ) ++p;
681 return 0; // extra junk
683 return 1; // number with exponent
687 Allocate and reformat a numeric string into one that is valid
688 by JSON rules. If the string is not numeric, return NULL.
689 Caller is responsible for freeing the buffer.
691 char* jsonScrubNumber( const char* s ) {
692 if( !s || !*s ) return NULL;
694 growing_buffer* buf = buffer_init( 64 );
696 // Skip leading white space, if present
698 while( isspace( (unsigned char) *s ) ) ++s;
700 // Skip leading plus sign, if present, but keep a minus
704 buffer_add_char( buf, '-' );
716 // Skip any leading zeros
718 while( '0' == *s ) ++s;
720 // Capture digits to the left of the decimal,
721 // and note whether there are any.
723 int left_digit = 0; // boolean
725 if( isdigit( (unsigned char) *s ) ) {
726 buffer_add_char( buf, *s++ );
730 while( isdigit( (unsigned char) *s ) )
731 buffer_add_char( buf, *s++ );
733 // Now we expect to see a decimal point,
734 // an exponent, or end-of-string.
742 // Add a single leading zero, if we need to
745 buffer_add_char( buf, '0' );
746 buffer_add_char( buf, '.' );
749 if( ! left_digit && ! isdigit( (unsigned char) *s ) )
751 // No digits on either side of decimal
757 // Collect digits to right of decimal
759 while( isdigit( (unsigned char) *s ) )
760 buffer_add_char( buf, *s++ );
767 // Exponent; we'll deal with it later, but
768 // meanwhile make sure we have something
772 buffer_add_char( buf, '1' );
776 // Unexpected character; bail out
782 if( '\0' == *s ) // Are we done yet?
783 return buffer_release( buf );
785 if( 'e' != *s && 'E' != *s ) {
787 // Unexpected character: bail out
793 // We have an exponent. Load the e or E,
794 // and the sign if there is one.
796 buffer_add_char( buf, *s++ );
798 if( '+' == *s || '-' == *s )
799 buffer_add_char( buf, *s++ );
801 // Collect digits of the exponent
803 while( isdigit( (unsigned char) *s ) )
804 buffer_add_char( buf, *s++ );
806 // There better not be anything left
813 return buffer_release( buf );