Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - .toJSON

I am a newbie to JSON & hence I am not sure what $.toJSON(params) means.

Please explain what this does.

like image 526
SoftwareGeek Avatar asked May 12 '10 13:05

SoftwareGeek


2 Answers

It could be this jQuery plugin

var myObj = {};
myObj.propA = "a";
myObj.propB = "b";
myObj.propC = "c";
var jsonString = $.toJSON(myObj); // same as jQuery.toJSON(myObj)
// output:  '{ "propA" : "a", "propB" : "b", "propC" : "c" }'
like image 174
Rebecca Chernoff Avatar answered Oct 08 '22 21:10

Rebecca Chernoff


See: http://www.json.org/js.html

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);

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

So if you have a $.toJSON() method, it could be a badly implemented function to "stringify", or it could be a method that returns the "JSON Representation" of $

like image 28
gnarf Avatar answered Oct 08 '22 19:10

gnarf