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/
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 $.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With