Tom Luijten
Tom Luijten

Reputation: 195

Placing JSON data in a variable

I am creating an autocomplete form that fills in your location based on your zipcode. This is the code I have to get a JSON with the information based on my zipcode:

var client = new XMLHttpRequest();
client.open("GET", "http://api.zippopotam.us/nl/1012", true);
client.onreadystatechange = function() {
    if(client.readyState == 4) {
        // alert(client.responseText);
        var jsonObj = [client.responseText]

    };
};

client.send();

Now I only need the location entry of the json. But for some reason I cant figure out how to aquire it in a variable. Basicly what I am aiming for is to get something like:

var location = 'Amsterdam'

Thanks!

Upvotes: 0

Views: 77

Answers (3)

Pablo Lozano
Pablo Lozano

Reputation: 10342

I've checked the response of requesting a GET to http://api.zippopotam.us/nl/1012 and this is the response:

{
    "post code" : "1012",
    "country" : "Netherlands",
    "country abbreviation" : "NL",
    "places" : [{
            "place name" : "Amsterdam Binnenstad en Oostelijk Havengebied",
            "longitude" : "4.9027",
            "state" : "Noord-Holland",
            "state abbreviation" : "NH",
            "latitude" : "52.3666"
        }
    ]
} 

So you will need to do something like the following:

var jsonResponse= JSON.parse(client.responseText);
var locations=jsonResponse.places; //an array!
if (places.length) {
  var firstLocation=locations[0]['place name'];
}

Upvotes: 3

wouter140
wouter140

Reputation: 255

Could you post what you get returned from XML request. To parse a json in javascript you could use:

var jsonraw = JSON.parse(jsonobj)

This way, you can select something from the json with:

var location = jsonraw['location']

Replace location with what you get returned from the json.

Upvotes: 2

MoLow
MoLow

Reputation: 3084

use JSON.parse function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

client.onreadystatechange = function() {
    if(client.readyState == 4) {
        var jsonObj = JSON.parse(client.responseText);
    };
};

and it wouldn't hurt to wrap that with a try, just in case the server dose not return a valid json

Upvotes: 1

Related Questions