-2

I want to parse json to js object with data. this is my simple example :

var IsTrue = true;
var Number = 9;
var Object = { a : 1};
var Array = [10,6];

var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Array}';
var js = JSON.parse(jStr);
console.log(js);

I work in this jsfiddle : http://jsfiddle.net/n4tLgp5k/1/

I get error :

Uncaught SyntaxError: Unexpected token I

i wish i can parse json to js object and variable in object initialized value with initialized variable before.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
yozawiratama
  • 4,209
  • 12
  • 58
  • 106
  • Don't use `eval()`, use `JSON.parse`, `JSON.stringify` on object [**Demo**](http://jsfiddle.net/n4tLgp5k/2/) – Tushar Nov 30 '15 at 06:20

3 Answers3

1

You have reference to variable inside the string so you can't parse it using JSON.parse(). Convert the string to valid JSON, you can do it usingJSON.stringify().

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var jStr = '{"ask" : ' + JSON.stringify(IsTrue) + ', "value" :' + JSON.stringify(Number) + ', "obj" : ' + JSON.stringify(Object) + ', "arr" : ' + JSON.stringify(Array) + '}';
var js = JSON.parse(jStr);
console.log(js);

If you just need to create the object then you can use object literals and if need json string you can use JSON.stringify()

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var js = {
  ask: IsTrue,
  value: Number,
  obj: Object,
  arr: Array
};

console.log(js);

Also there is baddest way using eval() but I will not prefer this method .

Why is using the JavaScript eval function a bad idea?

var IsTrue = true;
var Number = 9;
var Object = {
  a: 1
};
var Array = [10, 6];

var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Array}';
var js = eval('(' + jStr + ')');
console.log(js);
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You need a pure string before parsing.

var IsTrue = true,
    Number = 9,
    Object = { a : 1},
    Array = [10,6];

var jStr = {"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Array};
var js = JSON.parse(JSON.stringify(jStr));
console.log(js);

But I am not sure why you want to do this.

Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

Unless you have a specific reason for using a string, why not use an object literal like this?

var IsTrue = true;
var Number = 9;
var Object = { a : 1};
var Array = [10,6];

var js = {
    "ask" : IsTrue, 
    "value" : Number, 
    "obj" : Object, 
    "arr" : Array
};
console.log(js);

Although you should avoid using types as variable names. Number, Object, Array are all terrible variable names. If it doesn't cause a parse error it's certainly going to confuse someone sometime. And that someone might be your future self.

Anthony Manning-Franklin
  • 4,408
  • 1
  • 18
  • 23