Wednesday, October 6, 2010

XPages: Bug in fromJson (with fix)

Update 07.10.10: I added a by-value copy method

toJson can convert most JavaScript objects to JSON. fromJson can not convert back all JSON strings that toJson creates.

Example:
var arrayJson = toJson( [1,2,3] ); // "[1,2,3]"
fromJson( arrayJson ) // fails
If you try the same in Firefox, which has implemented the JSON API, everything works:
var arrayJson = JSON.stringify( [1,2,3] ); // "[1,2,3]"
JSON.parse( arrayJson ) // [1,2,3]
I've created a simple wrapper-class that works around this bug:
var JSON = {
// Makes a by-value copy of the object
copy: function( object ){
try {
// Faster way to copy arrays
if( object && typeof object.concat === 'function' ){ return object.concat(); }

return this.parse( this.stringify( object ) );
} catch( e ){ /*Debug.logException( e );*/ }
},

// Converts object to JSON string
stringify: function( object ){
try {
return toJson( object );
} catch( e ){ /*Debug.exception( e );*/ }
},

// Parses JSON to JS object
parse: function( JSON ){
try {
return fromJson( '{"values":' + JSON + '}' ).values;
} catch( e ){ /*Debug.exception( e );*/ }
}
}
It saddens me that there are so many "simple" bugs in the XPages API. :\

Share and enjoy!

1 comments:

Paul Hannan said...

Thanks Tommy. I've create a bug 'PHAN89ZBLE' to track this and proposing to get it addressed in 853.