François
François

Reputation: 3

JSON parsing issue with Javascript

I have a (probably) silly problem, but I can't undertand what's wrong ...
I request an AWS API Gateway URL, I have a json-formatted response, I parse it, but then when I want to get the value of a specific JSON element I get "undefined" instead of the element's value.

Here is my code :

var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            jsonData = JSON.parse(xhr.responseText);
            data = jsonData.coord;
            document.write(data);
        }
    }
    xhr.open('GET', "https://[mon-url]", true);
    xhr.send();

The API response is parsed using

jsonData = JSON.parse(xhr.responseText)
document.write(jsonData)

give the following output :

{
  "coord": {
    "lon": 2.35,
    "lat": 48.85
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 291.97,
    "pressure": 1019,
    "humidity": 56,
    "temp_min": 288.15,
    "temp_max": 295.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 3.1,
    "deg": 60
  },
  "clouds": {
    "all": 0
  },
  "dt": 1495747800,
  "sys": {
    "type": 1,
    "id": 5615,
    "message": 0.0022,
    "country": "FR",
    "sunrise": 1495684591,
    "sunset": 1495741168
  },
  "id": 2988507,
  "name": "Paris",
  "cod": 200
}

But if I try to get a specific element's value, for example using document.write(jsonData.coord) I get "undefined" as a value.

Can someone help me understand why I can't correctly parse my JSON data ?

Thanks !

Upvotes: 0

Views: 694

Answers (2)

Gokhan Kurt
Gokhan Kurt

Reputation: 8277

The data you are getting from the server is a string of JSON data. You should either change how the response is returned, or you have to parse the JSON twice.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        jsonData = JSON.parse(xhr.responseText);
        jsonData = JSON.parse(jsonData);
        data = jsonData.coord;
        document.write(data);
    }
}
xhr.open('GET', "https://[mon-url]", true);
xhr.send();

Upvotes: 1

koszyq
koszyq

Reputation: 151

use JSON.parse if response is a string

Upvotes: 0

Related Questions