If I defined an object in JS with:
var j={\"name\":\"binchen\"};
How can I convert the object to JSON? The output string should be:
For debugging in Node JS you can use util.inspect(). It works better with circular references.
var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));
JSON.stringify
turns a Javascript object into JSON text and stores that JSON text in a string.
The conversion is an Object to String
JSON.parse
turns a string of JSON text into a Javascript object.
The conversion is a String to Object
var j={"name":"binchen"};
to make it a JSON String following could be used.
JSON.stringify({"key":"value"});
JSON.stringify({"name":"binchen"});
For more info you can refer to this link below.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If you're using AngularJS, the 'json' filter should do it:
<span>{{someObject | json}}</span>
JSON.stringify(j, null, 4)
would give you beautified JSON in case you need beautification also
The second parameter is replacer. It can be used as Filter where you can filter out certain key values when stringifying. If set to null it will return all key value pairs
So in order to convert a js object to JSON String:
The simple syntax for converting an object to a string is
JSON.stringify(value)
The full syntax is: JSON.stringify(value[, replacer[, space]])
Let’s see some simple examples. Note that the whole string gets double quotes and all the data in the string gets escaped if needed.
JSON.stringify("foo bar"); // ""foo bar""
JSON.stringify(["foo", "bar"]); // "["foo","bar"]"
JSON.stringify({}); // '{}'
JSON.stringify({'foo':true, 'baz':false}); /* "
{"foo":true,"baz":false}" */
const obj = { "property1":"value1", "property2":"value2"};
const JSON_response = JSON.stringify(obj);
console.log(JSON_response);/*"{ "property1":"value1",
"property2":"value2"}"*/
In angularJS
angular.toJson(obj, pretty);
obj: Input to be serialized into JSON.
pretty(optional):
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.
(default: 2)