118
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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
indianwebdevil
  • 4,879
  • 7
  • 37
  • 51
  • 2
    See this answers http://stackoverflow.com/questions/3904269/convert-object-to-json-string – powtac Jan 22 '12 at 19:00

8 Answers8

323

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.

Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
95

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: https://stackoverflow.com/a/13488998/1127761

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,
           }`;
bardiir
  • 14,556
  • 9
  • 41
  • 66
  • 13
    Or put a \ at the end of each line in the literal. – Phrogz Jan 22 '12 at 19:05
  • 3
    For multi-line strings, instead of single or double quotes, you can use ` (back-tick character. to the left of the #1 key). These are called 'template literals'. – Blue Aug 16 '16 at 15:08
  • 5
    Definitely: don't settle for this answer and look to the others. – AsTeR Aug 26 '16 at 14:04
  • 1
    Template literals are ECMA Script 2015 Standard. This question and answer is from 2012 already. But I'll edit it in :) – bardiir Jan 19 '17 at 13:50
  • Really? String concatenation from scratch is the best way to build JSON? I think the other answer should be the accepted answer. – rory.ap Jan 10 '19 at 20:12
  • Don't do this! Use answer from Akhil - https://stackoverflow.com/a/13488998/3948544 – Christopher Smit Jul 01 '20 at 08:03
  • @rory.ap No it's definitely not the best solution for creating a json string, more an answer about the original question - what is the problem with the code in the question - which is the string concatenation is done wrongly. For the purpose of creating JSON definitely use an object, I'll edit the answer to reflect that. – bardiir Apr 08 '21 at 17:11
  • @indianwebdevil maybe you might also want to change the accepted solution to the object stringify one :) – bardiir Apr 08 '21 at 17:22
66

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.

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
36

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.
Hidden
  • 369
  • 3
  • 2
17

Use JSON.stringify:

> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'
TimWolla
  • 31,849
  • 8
  • 63
  • 96
7

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);
SULFIKAR A N
  • 436
  • 4
  • 13
0

The Answer from @Akhil is still the best for me. one user asked how to do nested properties, and I wanted to expand the solution like this:

var obj = new Object();
var nameobj = new Object();
nameobj.firstname = "Raj";
nameobj.lastname = "whatever";
obj.name = nameobj;
obj.age  = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
Mike
  • 3
  • 4
-6

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 9
    JSON can have line breaks, but JavaScript string literal syntax cannot. –  Jan 22 '12 at 19:03
  • interally within a string, yeah, but not between key/value pairs. – Marc B Jan 22 '12 at 19:07
  • 1
    I think you're confusing JavaScript string literal syntax which cannot contain an unescaped newline character, and JSON markup. JSON markup can most certainly contain line breaks. –  Jan 22 '12 at 19:11
  • 1
    ...paste the code in your question into http://jsonlint.com *(without the etc.... of course)*. After clicking Validate, you'll see that it actually *inserts* newlines when it pretty-prints. –  Jan 22 '12 at 19:14