IvanLi
IvanLi

Reputation:

a question about eval in javascript

thank you. here is the correct question:

{
    "VID":"60",
    "name":"\u4f1a\u9634",
    "requireLevel":"20",
    "levelMax":"5",
    "venationRequirement":"0",
    "description":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad8[Affect1]\u70b9",
    "cost":{"1":"240","2":"360","3":"400","4":"600","5":"720"},
    "difficult":{"1":"1024","2":"973","3":"921","4":"870","5":"819"},
    "affect":{"1":"200","2":"500","3":"900","4":"1400","5":"2000"},
    "descriptions":{
        "1":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad8200\u70b9",
        "2":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad8500\u70b9",
        "3":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad8900\u70b9",
        "4":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad81400\u70b9",
        "5":"\u6c14\u6d77\u4e0a\u9650\u63d0\u9ad82000\u70b9"
    }
}

i used json_encode() in php ,and ajax request to get the response text.

but when i use eval() to parse the response text. it's wrong.

moonshadow and james gregory has answered this question at the comments below.thank you again.

Upvotes: 1

Views: 241

Answers (5)

Vasil
Vasil

Reputation: 38106

Using json is a much better solution for this.

Upvotes: 0

moonshadow
moonshadow

Reputation: 89055

Javascript gets a little confused about what, in what context, it is parsing. Prepend a '(' and append a ')' before passing the string to eval() to force it to parse the whole thing as an expression.

(Your question as posed is also missing labels for the outer associative array, as others have pointed out, however the sample data you've provided clarifies the actual problem).

Upvotes: 3

Jonas
Jonas

Reputation:

If your second example is an attempt to create an object with two nested objects, you're missing the names for the properties of the outer object, e.g.

var s = '{ "FirstSubObject" : {"a":1}, "SecondSubObject":{"b":2}}';

Upvotes: 2

James Gregory
James Gregory

Reputation: 14223

Your second one is wrong because you're evaluating a hash, for it to work you'd need to rewrite it to be something like:

var s = '{"first": {"a":1}, "second": {"b":2}}';

Upvotes: 4

Ruben Bartelink
Ruben Bartelink

Reputation: 61795

The [] syntax is explicitly for creating arrays whereas {} has a completely different meaning (it thinks you're trying to create a function/block)

Upvotes: 0

Related Questions