Anshul
Anshul

Reputation: 7964

How do I access JSON elements through javascript?

The JSON file I have is following:

{
  "root": {
    "Quizsize": null,
    "{urn:abc.com/xmlns/mona/page}page": [
      {
        "@xid": "page1623",
        "@title": "Quiz Landing Page",
        "{urn:abc.com/xmlns/mona/page}comment": null,
        "{urn:abc.com/xmlns/mona/page}skills": null,
        "{urn:abc.com/xmlns/mona/page}info": {
          "{urn:abc.com/xmlns/mona/common}property": {
            "@name": "quiz_landing",
            "@value": "true"
          }
        }
      }
    ]
  }
}
}

I am loading this JSON file using :

var jsondata = eval("("+chapterRequest.responseText+")") ;
Root = jsondata.root

Now I want to access @xid which is "page1623 and @name which is "quiz_landing". I dont know how to do this,Please help.

Thanks

Upvotes: 0

Views: 913

Answers (2)

Steve Wang
Steve Wang

Reputation: 1824

JSON.parse(x) is better than eval(x), for one. It is not supported natively by some browsers though. If you want to access @xid, "urn:abc.com/xmlns/mona/page}page" points to an array whose first element is an object.

So use Root["{urn:abc.com/xmlns/mona/page}page"][0]["@xid"]. Or mix bracket and dot notation. Your choice, really.

Upvotes: 4

entonio
entonio

Reputation: 2173

When the key isn't a valid identifier, you use object['key'] instead of object.key, so jsondata.root['{urn:abc.com/xmlns/mona/page}page'][0]['@xid'].

Upvotes: 1

Related Questions