Wednesday, September 29, 2010

XPages: SSJS code snippet that lets you parse/stringify JS<->JSON

Update: I got word from Philippe Riand that fromJson/toJson/isJson is implemented in the XPages runtime. Apparently it has been available from 8.5.1.

Example usage:
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
---

A while back, I ported a script written for Rhino to SSJS that lets you parse JSON to JS objects/serialize JS objects to a JSON string. I've found it quite useful, so I thought I should share it with you.

I can't remember where I found the Rhino script, but the original source code that the Rhino script is based on is linked to at the bottom of this page: http://www.json.org/js.html

The original script was written/maintained by Douglas Crockford, and should prevent script injection, e.g. database.getAllDocuments().removeAll(true).

The script


Share and enjoy!

6 comments:

Philippe Riand said...

FYI, the XPages runtime includes new global methods: toJson/fromJson/isJson. Those are very efficient as they use the internal JS engine routines

Unknown said...

Server Side? 8.5.2?

Is fromJson secured (script injection)?

Philippe Riand said...

Yes it is. In fact, the parser uses a subset of the grammar that only allows what is defined at http://www.json.org/. Also, the JSON string is not evaluated using 'eval()' but directly processed by this specific parser.
It is server side, 8.5.1. ECMA also came with a spec for it.

Unknown said...

Do you plan on adding the optional reviver parameter that's specified in the ECMA standard?

http://wiki.ecmascript.org/doku.php?id=es3.1:json_support

Without it, one has to write a secondary JS loop to deal with dates when serializing/deserializing.

Having this implemented on the java side would lead to better performance.

Philippe Riand said...

Good idea, will look at that

Unknown said...

Great!

Not sure if you plan to implement this in a future version of the XPages Extension Library, but if so, I'd be very grateful. We already have the library running on our development server.

As soon as the rest of the servers are upgraded to 8.5.2, I plan to install it on the rest of them.

Keep up the good work!