All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j = {
"name": "binchen"
};
console.log(JSON.stringify(j));
Answer from Andris on Stack OverflowAll current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j = {
"name": "binchen"
};
console.log(JSON.stringify(j));
With JSON.stringify() found in json2.js or native in most modern browsers.
JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as "\t" or " "), it contains the characters used to indent at each level.
How do I convert a JavaScript object to JSON?
What is the difference between a JavaScript object and JSON?
How do I convert an array of JavaScript objects to JSON?
Quite literally, JSON is a stricter format for what is basically the right-hand side of a Javascript variable assignment. It's a text-based encoding of Javascript data:
var foo = ...json goes here ...;
JSON can be ANY valid Javascript data-only structure. A boolean, an int, a string, even arrays and objects. What JSON ISN'T is a general serialization format. Something like this
var foo = new Date();
json = JSON.stringify(foo); // json gets the string "2016-08-26 etc..."
newfoo = JSON.parse(json); // newfoo is now a string, NOT a "Date" object.
will not work. The Date object will get serialized to a JSON string, but deserializing the string does NOT give you a Date object again. It'll just be a string.
JSON can only represent DATA, not CODE. That includes expressions
var foo = 2; // "2" is valid json
var foo = 1+1; // invalid - json does not have expressions.
var foo = {"bar":["baz"]}; // also valid JSON
var foo = [1,2,3+4]; // fails - 3+4 is an expression
To convert JS data object to JSON , you can use JSON.stringify()
Exmaple
Input :-
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
JSON.stringify(person)
Output:
"{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue"}"