Parse nested JSON with JQuery
Hi,
I'm using the following code to parse a JSON and output to a web page:
- <body>
-
- <section>
- </section>
- <script>
-
- var section = document.querySelector('section');
- var requestURL = 'http://localhost/working/points_data.json';
- var request = new XMLHttpRequest();
- request.open('GET', requestURL);
- request.responseType = 'text';
- request.send();
- request.onload = function() {
- var JsonText = request.response;
- var JsonData = JSON.parse(JsonText);
- showPoints(JsonData);
- }
-
- function showPoints(jsonObj) {
- var points_arr = jsonObj['ref'];
- for(var i = 0; i < points_arr.length; i++) {
- var myArticle = document.createElement('article');
- var myH2 = document.createElement('h2');
- var myPara1 = document.createElement('p');
- var myPara2 = document.createElement('p');
- var myPara3 = document.createElement('p');
- var myList = document.createElement('ul');
- myH2.textContent = points_arr[i].name;
- myPara1.textContent = 'Display: ' + points_arr[i].display;
- myPara2.textContent = 'href: ' + points_arr[i].href;
- myPara3.textContent = 'Is:' + points_arr[i].is;
- myArticle.appendChild(myH2);
- myArticle.appendChild(myPara1);
- myArticle.appendChild(myPara2);
- myArticle.appendChild(myPara3);
- myArticle.appendChild(myList);
- section.appendChild(myArticle);
- }
- }
- </script>
- </body>
My text/sample JSON looks like this, which works.
- {
- "name": "points",
- "display": "points",
- "href": "http://#",
- "ref": [
- {
- "name": "A1",
- "display": "A1",
- "href": "A1/",
- "is": "A1"
- },
- {
- "name": "B1",
- "display": "B1",
- "href": "B1",
- "is": "B1"
- },
- {
- "name": "C1",
- "display": "C1",
- "href": "C1",
- "is": "C1"
- }
- ]
- }
But, my actual live data I believe is nested like so, and doesn't display any output to the website. Is there a way to handle the nested "
obj": ?
Or, alternatively, is there a better way to look through JSON, and output to a web page.
- {
- "obj": {
- "name": "points",
- "display": "points",
- "href": "http://##",
- "is": "/is",
- "ref": [
- {
- "name": "AI",
- "display": "AI",
- "href": "AI/",
- "is": "is"
- },
- {
- "name": "AI1",
- "display": "AI1",
- "href": "AI1/",
- "is": "/is",
- },
- {
- "name": "BV",
- "display": "BV",
- "href": "BV/",
- "is": "/is",
- } ],
- "int": [
- {
- "name": "meta",
- "display": "meta",
- "href": "meta/",
- "is": "/is",
- "writable": "true",
- "val": "1"
- },
- {
- "name": "status",
- "display": "status",
- "href": "status/",
- "is": "/is",
- "val": "0"
- } ]
- }
- }
Many thanks, J