Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign JSON string to Javascript variable?

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/

like image 377
4thSpace Avatar asked Jul 12 '15 20:07

4thSpace


People also ask

How can I get data from JSON to variable?

This will do it: var json = (function () { var json = null; $. ajax({ 'async': false, 'global': false, 'url': my_url, 'dataType': "json", 'success': function (data) { json = data; } }); return json; })(); The main issue being that $.

Can you use JSON in JavaScript?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.


2 Answers

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);
like image 108
Carl K Avatar answered Oct 12 '22 01:10

Carl K


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);
like image 27
Dylan Watt Avatar answered Oct 12 '22 02:10

Dylan Watt