window.onload = function(){
var obj = \'{
\"name\" : \"Raj\",
\"age\" : 32,
\"married\" : false
}\';
var va
The way i do it is:
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
I guess this way can reduce chances for errors.
Use JSON.stringify
:
> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'
json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}
.
But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.
This can be pretty easy and simple
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
//convert object to json string
var string = JSON.stringify(obj);
//convert string to Json Object
console.log(JSON.parse(string)); // this is your requirement.
I think this way helps you...
var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);
Javascript doesn't handle Strings over multiple lines.
You will need to concatenate those:
var obj = '{'
+'"name" : "Raj",'
+'"age" : 32,'
+'"married" : false'
+'}';
You can also use template literals in ES6 and above: (See here for the documentation)
var obj = `{
"name" : "Raj",
"age" : 32,
"married" : false,
}`;