0

I'm playing with wikipedia json, so… I have this object:

Object {query: Object}
query: Object
    pages: Object
        869994: Object
            ns: 0
            pageid: 869994
            revisions: Array[1]
            title // <- I need you baby

retrieved with an id (in this case, 869994). Now I want to retrieve the title, so i should use

    $.getJSON(myIdUrl, function(data) {

    var obj = 'data.query.pages.' + id + '.title';

    console.log(obj); // it prints data.query.pages.869994.title should be right..

    var title = eval(obj); // now I want to assign obj title value to my variable

    // something else…      
}); 

I get an error, "SyntaxError: Unexpected number '.869994' "…

I think I misunderstood the eval() function, or just making the wrong path to retrieve obj data…

suggestions? thank you!

1 Answer 1

2

Change this:

var obj = 'data.query.pages.' + id + '.title';

to this:

var obj = 'data.query.pages["' + id + '"].title';

The reason is that the parser is confused; when you dereference an object it's expecting an identifier, not a literal number.

var x = {};
x.5 = "test"; // <- notice this seems very unnatural
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.