views:

212

answers:

3

how can i convert a JSON Object to JSONtext in a javascript function. i should pass the JSONtext as a string to JSP.

+1  A: 

Quoth Crockford (http://www.json.org/js.html):

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. ...

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

And then he develops the JSON prototype in the rest of the article.

The versions of Gecko used in Firefox 3 and 3.5 support JSON natively (https://developer.mozilla.org/En/JSON), which may be useful if your project is limited to a recent Gecko-based application.


As pointed out below, the interesting part about the text generator (not parser) is at http://www.json.org/json2.js and introduced with

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

Cyclic data structures and objects that aren't usefully serialized are obviously the only big caveats there.

Anonymous
A: 

It is worth mentioning that Anonymous's link (http://www.json.org/js.html) will point you in the right direction because the page also includes information about how to stringify a JavaScript data structure into JSON text:

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text.

In particular, look for the link at the bottom of the page that points to an open source JSON parser and JSON stringifier.

Bobby Eickhoff
A: 

There are two sample methods in Crockford's library (as raised by @Anonymous):

JSON string to object:

var obj = JSON.parse('{ property:"value" }');
alert (obj.property);

// value

Object to JSON string:

var str = JSON.stringify({ property:"value" })
alert (str);

//{ property:"value" }

There are also built in methods to do this in most of the major frameworks.

Keith
Library at http://www.json.org/json.js
Keith