13

What is the correct way to assign a JSON string to a variable? I keep getting EOF errors.

var somejson = "{
    "key1": "val1",
    "key2": "value2"
}";

http://jsfiddle.net/x7rwq5zm/1/

4thSpace
  • 43,672
  • 97
  • 296
  • 475

4 Answers4

19

You have not escaped properly. You make sure you do:

var somejson = "{ \"key1\": \"val1\",\"key2\": \"value2\"}";

The easier way would be to just convert an existing object to a string using JSON.stringify(). Would recommend this as much as possible as there is very little chance of making a typo error.

var obj = {
    key1: "val1",
    key2: "value2"
};

var json = JSON.stringify(obj);
Carl K
  • 974
  • 7
  • 18
  • 3
    Your answer is definitely valid, but probably easier to use `'` than escaping everything. – Dylan Watt Jul 12 '15 at 20:18
  • good to know. Out of curiosity, what environments? I've never run into it. I'd assume it would be instantiated as a string, and any later parse would have no knowledge of how that string was made. – Dylan Watt Jul 12 '15 at 20:27
  • @DylanWatt meant to click edit, clicked delete. Tired, lol. I've run into some issues in nodejs on another project I worked on using single quotes. That being said, that may no longer be an issue in the newer versions >0.10.x – Carl K Jul 12 '15 at 20:30
9

If you want the string, not the object (note the ' instead of ")

var somejson =  '{ "key1": "val1", "key2": "value2" }';

If you want a string declared with multiple lines, not the object (newline is meaningful in Javascript)

var somejson =  '{'
 + '"key1": "val1",' 
 + '"key2": "value2"' 
 + '}';

If you want the object, not the string

var somejson =  { "key1": "val1", "key2": "value2" };

If you want a string generically

var somejson =  JSON.stringify(someobject);
Dylan Watt
  • 3,357
  • 12
  • 16
0

I think you should use JSON.stringify function. See the answers here - Convert JS object to JSON string

var somejson = {
    "key1": "val1",
    "key2": "value2"
};
somjson = JSON.stringify(somejson);
Community
  • 1
  • 1
Ankur Anand
  • 535
  • 2
  • 9
0

Best way to assign JSON string value to a variable.

var somejson = JSON.parse('{"key1": "val1","key2": "value2"}')
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77