pencilCake
pencilCake

Reputation: 53243

Why eval() isn't working here to deserialize such a simple JSON object?

I am trying to use eval() function to deserialize this JSON text by using eval function.

var personJSON = {
  "FirstName": "Burak",
  "LastName": "Ozdogan",
  "Id": "001",
  "Department": "Information Technologies"
};

var personBurakOzdogan = eval('(' + personJSON + ')');

But I am getting this error:

*Microsoft JScript compilation error: Expected ']'*

Is there something that I skip which I cannot catch?

Thanks

Upvotes: 3

Views: 1202

Answers (4)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298848

you are not dealing with a string, but with a json object. You are trying to evaluate a json object as string to create a json object.

var personJSON =
  '{"FirstName":"Burak","LastName":"Ozdogan","Id":"001","Department":"Information Technologies"}';

var personBurakOzdogan = eval('(' + personJSON + ')');

this should work, although it doesn't make to much sense. this makes more sense:

var personBurakOzdogan = {
  "FirstName": "Burak",
  "LastName": "Ozdogan",
  "Id": "001",
  "Department": "Information Technologies"
};

Upvotes: 2

user3054475
user3054475

Reputation: 1

You have to pass to the variable a string type as the code seen below:

var personJSON = '{"FirstName":"Burak","LastName":"Ozdogan","Id":"001","Department":"Information Technologies"}';

Upvotes: 0

max
max

Reputation: 39

Try to check if your personJSON is a wrapper that CONTAINS the real json. For example, try to write:

var person = eval('(' + personJSON.Person + ')')

where Person is the class serialized by the service.

OR

try this:

var person = eval('(' + personJSON.GetPersonResult + ')')

where GetPerson is the method name in the service, plus Result.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038750

What you have is not JSON text. It is already a JSON object. So you don't need to use eval at all. You can directly access and manipulate its properties:

alert(personJSON.FirstName);

Upvotes: 6

Related Questions