简体   繁体   中英

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

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.

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'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM