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:
The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.
function simpleJSONstringify(obj) {
var prop, str, val,
isArray = obj instanceof Array;
if (typeof obj !== "object") return false;
str = isArray ? "[" : "{";
function quote(str) {
if (typeof str !== "string") str = str.toString();
return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
}
for (prop in obj) {
if (!isArray) {
// quote property
str += quote(prop) + ": ";
}
// quote value
val = obj[prop];
str += typeof val === "object" ? simpleJSONstringify(val) : quote(val);
str += ", ";
}
// Remove last colon, close bracket
str = str.substr(0, str.length - 2) + ( isArray ? "]" : "}" );
return str;
}
Use this,
var j={"name":"binchen"};
var myJSON = JSON.stringify(j);
Simply use JSON.stringify(your_variableName) it will convert your JSON object to string and if you want to convert string to object use JSON.parse(your_variableName)
Just use JSON.stringify
to do such conversion - however remember that fields which have undefined
value will not be included into json
var j={"name":"binchen", "remember":undefined, "age": null };
var s=JSON.stringify(j);
console.log(s);
The field remember
'disappear' from output json
use JSON.stringify(param1, param2, param3);
What is: -
param1 --> value to convert to JSON
param2 --> function to stringify in your own way. Alternatively, it serves as a white list for which objects need to be included in the final JSON.
param3 --> A Number data type which indicates number of whitespaces to add. Max allowed are 10.
One custom defined for this , until we do strange from stringify method
var j={"name":"binchen","class":"awesome"};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j)
{
json += dq+x+dq+":"+dq+j[x]+dq;
count++;
if(count<last)
json +=",";
}
json+="}";
document.write(json);
OUTPUT
{"name":"binchen","class":"awesome"}
LIVE http://jsfiddle.net/mailmerohit5/y78zum6v/