Xomino

Domino with the new improved X

SSJS JSON parsing part deux

Posted by MarkyRoden on December 19, 2013

Yesterday’s blog post about adding json2.js created a discussion on it’s use and Johann pointed out that there were already JSON parsing functions baked into XPages SSJS. Phil Riand added them back in 8.5.1 and it has actually been mentioned a number of times on various Blogs. So apologies to all for me not knowing about it. I guess I never bothered to look as I knew how to do it with the json2.js :)

Julian Buss added a wiki post about it years ago - http://xpageswiki.com/web/youatnotes/wiki-xpages.nsf/dx/Work_with_ServerSide_JavaScript

	var json = toJson( {a:[1,2,3]} ) //-> '{"a":[1,2,3]}'
	var jsObj = fromJson( '{"a":[1,2,3]}' ) //-> {a:[1,2,3]}
	isJson( '{"a":[1,2,3]}' ) //-> true

So ok I learned something new – happens a lot – but then I also got to thinking – as I mentioned yesterday JSON.parse and JSON.stringify are so ubiquitous I decided to write some code to minic the coding standard in SSJS. This code serves zero purpose other than to make the usage of JSON consistent between SSJS and CSJS. It is a short version of what I wrote about yesterday and does not require the addition of the json2.js to the database.

	if (typeof JSON !== 'object') {
		JSON = {};
	}
	JSON = {
		parse: function(str){
			return fromJson(str)
		},
		stringify: function(obj){
			return toJson(obj)
		}
	}
About these ads

2 Responses to “SSJS JSON parsing part deux”

  1. Dan O'Connor said

    Also.. If you look at the SBT code on OpenNTF there is really nice ‘navigator’ functionality built in.. It basically allows you to pass an object (JSON object OR XML document) into the navigator and then provide a path to the value you want… I don’t recall the exact code but in pseudo terms:

    var navigator = new sbt.JSONNavigator(json);
    var value = navigator.value(“user/address/city”);

    This will in turn return either the value of the attribute at the location provided or null.. This is much more convenient than the many if(user != null){if(user.address != null){…. type steps you’d have to go through to make your code robust.. This nifty little util takes care of it for you… And an added bonus, it is available in SSJS and in Java! :-)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: