views:

8875

answers:

2

The people on this website seem to know everything so I figured I would ask this just in case:

Is there a method/function in prototype that converts a JSON object to a string that you can store in a cookie?

If not,..i'll just use another external library.

Thanks, Andrww

A: 

Assuming you're speaking of Prototype JavaScript framework, why not just use JavaScript's own JSON functionality? JSON does after all stand for JavaScript Object Notation.

P Arrayah
Plain Javascript can go from JSON string to object, but doesn't have a function to JSON-encode an object to a string
Greg
JavaScript doesn't have JSON functionality (neither encoding, nor safe decoding). Firefox 3.1 and IE 8 implemented Douglas Crockford's "json2" API, but for everything else you need a library.
orip
There's four libraries available at json.org for the functionality and from what I've read and understood JSON support already is in most mainline browsers (with the natural exception of IE7 of course), I'm a bit confused by this, for me this is like asking if I should drink water if I'm thirsty.
P Arrayah
Javascript natively accepts json, e.g. var foo = {}. What it doesn't do is string-to-object ('{}') or object-to-string (foo -> '{}')
Greg
Also it's not "safe" as you can do var foo = {"blah":someFunction()} - of course, this can be a very useful feature as well
Greg
+5  A: 

Sure there is: Prototype JSON

var data = {name: 'Violet', occupation: 'character', age: 25 };
var myString = Object.toJSON(data);
// myString = '{"name": "Violet", "occupation": "character", "age": 25}'

Then shove myString into your cookie

Greg
what is Object?Do I have to instantiate this earlier? Do i need some extra prototype library?...because it is not being recognized.Andrew
Object is part of javascript - it must be something else that's not working. Either Prototype isn't loaded properly, or data (or whatever you called your argument) doesn't exist
Greg
hm...alright i'll take your word for it, prototype has to be loaded cuz i use all the $() and scriptaculous etc. ....so i don't know what it could be. all well, JSON.js it is.,...thanks for the answers
upon further inspection if I put the code inside a function it works! ...(i was just testing it outside any function)....:)
Hmmm it doesn't need to be inside a function but I guess there was something else going on (prototype loading afterwards or something)... glad it works though.
Greg
ya that's probably it for sure actually,...i'm using symfony so that probably loads the prototype library after the initial java. the world makes sense again. thanks.
More detailed information is available at http://www.prototypejs.org/learn/json
nertzy