0

I have a json file like this

{
    "doctors": [{
        "name": "...",
        "Section": "...",
        "Grade": "..."
    },
    {
        "name": "...",
        "Section": "...",
        "Grade": "..."
    }],
    "nurses": [{
        "name": "...",
        "Grade": "..."
    },
    {
        "name": "...",
        "Grade": "..."
    },
    {
        "name": "...",
        "Grade": "..."
    },
    {
        "name": "...",
        "Grade": "..."
    }]
}

Inside the script tag of the html file I have defined a loadData function that is called when a button is pressed.

function loadStaffData() {
        var xo = new XMLHttpRequest();
        xo.overrideMimeType("application/json");
        xo.open('GET', 'staff_data.json', true); 
        xo.onreadystatechange = function () {
            if (xo.readyState == 4 && xo.status == "200") {                  

              var X=JSON.parse(xo.responseText);
              console.log(X); //line 18
            }
          };
          xo.send(null);
        }

Right now I am only able to get the whole set of data in the json file. But I need to be ale to retrieve each doctor's/ nurse's name/ section/ gender separately. I tried typing xo.responseText('doctors'[0]) and even xo.responseText([0][0]), but none of them worked.

Edit I have also tried parsing the responseText: JSON.parse(xo.responseText). But I have got this error: JSON.parse: expected ',' or '}' after property value in object at line 18

The json file is on my local disc and I use firefox (developer edition) to get output.

  • The `responseText` is text. Parse it into an object before trying to access it like an object. – CertainPerformance May 24 '18 at 21:32
  • After you parse it, it's `data.doctors[i]` and `data.nurses[i]` – Barmar May 24 '18 at 21:34
  • Please see the edit I made to the main question. – Alpha Bravo Charlie ... May 24 '18 at 22:02
  • @MaYaNicolson I just have checked your JSON file content in your question. The structure is correct so `JSON.parse` should be executed without problems. Can you display the results of `xo.responseText` ? (simply do `console.log(xo.responseText)` and c/p over the output) – KarelG May 28 '18 at 08:15
  • I have solved the problem. There were soecial characters in the fields that had to be taken care of. I am not able to post my answer, becausse the question is marked and closed as a duplicate. – Alpha Bravo Charlie ... May 28 '18 at 08:20

1 Answers1

0

try:

JSON.parse(xo.responseText)["doctors"][0]

You need to parse the request response, then you can select the data.

SamHDev
  • 172
  • 1
  • 14