0

Here is my data file named "student.json":

[
    {
        "firstname": "Zack",
        "lastname": "F",
        "email": "zack@fire.com",
        "phone": "2021231234",
        "address": {
            "communication": "fire, Princeton, New Jersey",
            "permanent": "M"
        }
    },
    {
        "firstname": "Jersey",
        "lastname": "L",
        "email": "gzx95@gmail.com",
        "phone": "2571548741",
        "address": {
            "communication": "fire, Princeton, New Jersey",
            "permanent": "Y"
        }
    }
]

And I want to list these data. But I cannot retrieve data in the nested json, the address information. The following is my code, I tried to use eval() function to get data, but it does not work. I don't know why.

<script src="js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    $(function() {
        getDate();

        function getDate() {
            var temp = '';
            $.ajax({
                type: "get",
                url: "student.json",
                dataType: "json",
                success: function(res) {
                    var list = res;
                    console.log(list);
                    for(var $i = 0; $i < list.length; $i++) {
                        var obj = eval(list[$i]);
                        console.log(obj['address']['communication']);
                        temp +=
                            '<tr>' +
                            '<td>' + obj['firstname'] + '</td>' +
                            '<td>' + obj['lastname'] + '</td>' +
                            '<td>' + obj['email'] + '</td>' +
                            '<td>' + obj['phone'] + '</td>'+
                            '<td>' + obj['address']['communication'] + '</td>'+
                            '<td>' + obj['address']['permanent'] + '</td>'+
                            '</tr>';
                    }
                    $("#jsonTable tr:not(:first)").html(""); 
                    $("#jsonTable").append(temp);
                }
            });
        }
    });
</script>

Can anyone help?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Zexi Gong
  • 169
  • 11
  • 1
    You don't need to run `eval` on anything as it's already been parsed. So the line `var obj = eval(list[$i]);` should be `var obj = list[$i];` if you want to store a reference to the current list item. – JAAulde Dec 26 '20 at 23:07
  • Thanks JAAulde, I have tried without eval() before. It also does not work. Do you know how to get the values inside the nested json, the address? – Zexi Gong Dec 26 '20 at 23:11
  • 1
    There is no nested JSON. If the data you show is really what the server sends back, then when `success` runs, `res` is fully parsed and you just have a data structure (array of objects which have some properties that are also objects). If `i` is an index of the array, then `res[i].address.communication` or `res[i]['address']['communication']` are both ways of accessing the `communication` property of the current object's `address` property. If that's not working, something else is wrong. – JAAulde Dec 26 '20 at 23:15
  • 1
    And since you're making `list` a reference to `res`, and `$i` is your index, and `obj` is a reference to the object at that index, then there is no reason you shouldn't be able to access as `obj['address']['communication']` or `obj.address.communication`. – JAAulde Dec 26 '20 at 23:17
  • 1
    Tip: [Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) are thing now. You don't have to concatenate strings all the time. Also consider using `let` or `const` vs. `var` for better scope control. – tadman Dec 27 '20 at 01:45
  • 1
    JSON is a text format, like XML or CSV. Once you get it and it's been parsed, all you're left with is plain JavaScript arrays, objects, and primitive values. Since jQuery figured out you were receiving JSON, it went ahead and parsed the data for you. – Heretic Monkey Dec 27 '20 at 02:19
  • 1
    Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Heretic Monkey Dec 27 '20 at 02:20

1 Answers1

0

Here's a version that can be run within StackOverflow. The code uses a string in place of the json file.

I've simplified it to show some easier ways to handle the data.

// string to stand in for the JOSN file data
const studentsJSON = `[
    {
        "firstname": "Zack",
        "lastname": "F",
        "email": "zack@fire.com",
        "phone": "2021231234",
        "address": {
            "communication": "fire, Princeton, New Jersey",
            "permanent": "M"
        }
    },
    {
        "firstname": "Jersey",
        "lastname": "L",
        "email": "gzx95@gmail.com",
        "phone": "2571548741",
        "address": {
            "communication": "fire, Princeton, New Jersey",
            "permanent": "Y"
        }
    }
]`;

// get students from json file stand-in
function getStudents(callback) {
  callback(JSON.parse(studentsJSON));
}

// add all students to table
function addStudentsToTable(students) {

  // remove all rows from table
  jsonTable.innerHTML = '';

  // loop through each student object in the students array
  students.forEach(student => {

    // use destructuring to make accessing the student properties
    // easier
    const {
      firstname,
      lastname,
      email,
      phone
    } = student;
    const {
      communication,
      permanent
    } = student.address;

    // add a row at the bottom of the table
    const row = jsonTable.insertRow(-1);

    // add table cells to the row
    // and simplify using string template literals
    const rowCells = `
        <td>${firstname}</td>
        <td>${lastname}</td>
        <td>${email}</td>
        <td>${phone}</td>
        <td>${communication}</td>
        <td>${permanent}</td>`;
    row.innerHTML = rowCells;
  });
}

const jsonTable = document.getElementById('jsonTable');

// get the students data and add to table
function getDate() {
  getStudents(function(students) {
    addStudentsToTable(students)
  });
}

getDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<table id="jsonTable"></table>
terrymorse
  • 6,771
  • 1
  • 21
  • 27