How to create JSON string in JavaScript?

window.onload = function(){ var obj = '{ "name" : "Raj", "age" : 32, "married" : false }'; var val = eval('(' + obj + ')'); alert( "name : " + val.name + "\n" + "age : " + val.age + "\n" + "married : " + val.married );
}

In a code something like this, I am trying to create JSON string just to play around. It's throwing error, but if I put all the name, age, married in one single line (line 2) it doesn't. Whats the problem?

1

7 Answers

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.

1

Disclaimer: This is not an answer to follow for the best way how to create JSON in JavaScript itself. This answer mostly tackles the question of "what is the problem?" or WHY the code above does not work - which is a wrong string concatenation attempt in JavaScript and does not tackle why String concatenation is a very bad way of creating a JSON String in the first place.

See here for best way to create JSON:

Read this answer to understand why the code sample above does not work.

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, }`;
8

The function JSON.stringify will turn your json object into a string:

var jsonAsString = JSON.stringify(obj);

In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.

0

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.
0

Use JSON.stringify:

> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'
4

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

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.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like