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 unsigned long jsonObjectRemoveKey( jsonObject* dest, const char* key) {
444 if( dest && key && dest->type == JSON_HASH ) {
445 osrfHashRemove(dest->value.h, key);
452 Allocate a buffer and format a specified numeric value into it.
453 Caller is responsible for freeing the buffer.
455 char* doubleToString( double num ) {
458 size_t len = snprintf(buf, sizeof( buf ), "%.30g", num) + 1;
459 if( len < sizeof( buf ) )
460 return strdup( buf );
463 // Need a bigger buffer (should never be necessary)
465 char* bigger_buff = safe_malloc( len + 1 );
466 (void) snprintf(bigger_buff, len + 1, "%.30g", num);
471 char* jsonObjectGetString(const jsonObject* obj) {
474 if( obj->type == JSON_STRING )
476 else if( obj->type == JSON_NUMBER )
477 return obj->value.s ? obj->value.s : "0";
485 double jsonObjectGetNumber( const jsonObject* obj ) {
486 return (obj && obj->type == JSON_NUMBER && obj->value.s)
487 ? strtod( obj->value.s, NULL ) : 0;
490 void jsonObjectSetString(jsonObject* dest, const char* string) {
491 if(!(dest && string)) return;
492 JSON_INIT_CLEAR(dest, JSON_STRING);
493 dest->value.s = strdup(string);
497 Turn a jsonObject into a JSON_NUMBER (if it isn't already one) and store
498 a specified numeric string in it. If the string is not numeric,
499 store the equivalent of zero, and return an error status.
501 int jsonObjectSetNumberString(jsonObject* dest, const char* string) {
502 if(!(dest && string)) return -1;
503 JSON_INIT_CLEAR(dest, JSON_NUMBER);
505 if( jsonIsNumeric( string ) ) {
506 dest->value.s = strdup(string);
510 dest->value.s = NULL; // equivalent to zero
515 void jsonObjectSetNumber(jsonObject* dest, double num) {
517 JSON_INIT_CLEAR(dest, JSON_NUMBER);
518 dest->value.s = doubleToString( num );
521 void jsonObjectSetClass(jsonObject* dest, const char* classname ) {
522 if(!(dest && classname)) return;
523 free(dest->classname);
524 dest->classname = strdup(classname);
526 const char* jsonObjectGetClass(const jsonObject* dest) {
527 if(!dest) return NULL;
528 return dest->classname;
531 jsonObject* jsonObjectClone( const jsonObject* o ) {
532 if(!o) return jsonNewObject(NULL);
539 jsonObject* result = NULL;
543 result = jsonNewObject(NULL);
546 result = jsonNewObject(jsonObjectGetString(o));
549 result = jsonNewObject( o->value.s );
550 result->type = JSON_NUMBER;
553 result = jsonNewBoolObject(jsonBoolIsTrue((jsonObject*) o));
556 arr = jsonNewObject(NULL);
557 arr->type = JSON_ARRAY;
558 for(i=0; i < o->size; i++)
559 jsonObjectPush(arr, jsonObjectClone(jsonObjectGetIndex(o, i)));
563 hash = jsonNewObject(NULL);
564 hash->type = JSON_HASH;
565 itr = jsonNewIterator(o);
566 while( (tmp = jsonIteratorNext(itr)) )
567 jsonObjectSetKey(hash, itr->key, jsonObjectClone(tmp));
568 jsonIteratorFree(itr);
573 jsonObjectSetClass(result, jsonObjectGetClass(o));
577 int jsonBoolIsTrue( const jsonObject* boolObj ) {
578 if( boolObj && boolObj->type == JSON_BOOL && boolObj->value.b )
584 char* jsonObjectToSimpleString( const jsonObject* o ) {
592 value = strdup( o->value.s ? o->value.s : "0" );
596 value = strdup(o->value.s);
603 Return 1 if the string is numeric, otherwise return 0.
604 This validation follows the rules defined by the grammar at:
607 int jsonIsNumeric( const char* s ) {
609 if( !s || !*s ) return 0;
613 // skip leading minus sign, if present (leading plus sign not allowed)
618 // There must be at least one digit to the left of the decimal
620 if( isdigit( (unsigned char) *p ) ) {
623 // If the first digit is zero, it must be the
624 // only digit to the lerft of the decimal
626 if( isdigit( (unsigned char) *p ) )
631 // Skip oer the following digits
633 while( isdigit( (unsigned char) *p ) ) ++p;
646 // If there is a decimal point, there must be
647 // at least one digit to the right of it
649 if( isdigit( (unsigned char) *p ) )
654 // skip over contiguous digits
656 while( isdigit( (unsigned char) *p ) ) ++p;
660 return 1; // decimal fraction, no exponent
661 else if( *p != 'e' && *p != 'E' )
662 return 0; // extra junk, no exponent
666 // If we get this far, we have the beginnings of an exponent.
667 // Skip over optional sign of exponent.
669 if( '-' == *p || '+' == *p )
672 // There must be at least one digit in the exponent
674 if( isdigit( (unsigned char) *p ) )
679 // skip over contiguous digits
681 while( isdigit( (unsigned char) *p ) ) ++p;
684 return 0; // extra junk
686 return 1; // number with exponent
690 Allocate and reformat a numeric string into one that is valid
691 by JSON rules. If the string is not numeric, return NULL.
692 Caller is responsible for freeing the buffer.
694 char* jsonScrubNumber( const char* s ) {
695 if( !s || !*s ) return NULL;
697 growing_buffer* buf = buffer_init( 64 );
699 // Skip leading white space, if present
701 while( isspace( (unsigned char) *s ) ) ++s;
703 // Skip leading plus sign, if present, but keep a minus
707 buffer_add_char( buf, '-' );
719 // Skip any leading zeros
721 while( '0' == *s ) ++s;
723 // Capture digits to the left of the decimal,
724 // and note whether there are any.
726 int left_digit = 0; // boolean
728 if( isdigit( (unsigned char) *s ) ) {
729 buffer_add_char( buf, *s++ );
733 while( isdigit( (unsigned char) *s ) )
734 buffer_add_char( buf, *s++ );
736 // Now we expect to see a decimal point,
737 // an exponent, or end-of-string.
745 // Add a single leading zero, if we need to
748 buffer_add_char( buf, '0' );
749 buffer_add_char( buf, '.' );
752 if( ! left_digit && ! isdigit( (unsigned char) *s ) )
754 // No digits on either side of decimal
760 // Collect digits to right of decimal
762 while( isdigit( (unsigned char) *s ) )
763 buffer_add_char( buf, *s++ );
770 // Exponent; we'll deal with it later, but
771 // meanwhile make sure we have something
775 buffer_add_char( buf, '1' );
779 // Unexpected character; bail out
785 if( '\0' == *s ) // Are we done yet?
786 return buffer_release( buf );
788 if( 'e' != *s && 'E' != *s ) {
790 // Unexpected character: bail out
796 // We have an exponent. Load the e or E,
797 // and the sign if there is one.
799 buffer_add_char( buf, *s++ );
801 if( '+' == *s || '-' == *s )
802 buffer_add_char( buf, *s++ );
804 // Collect digits of the exponent
806 while( isdigit( (unsigned char) *s ) )
807 buffer_add_char( buf, *s++ );
809 // There better not be anything left
816 return buffer_release( buf );