jvillegas
jvillegas

Reputation: 71

how to convert a responseText into a json

I have as a xmlhttp.responseText that:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "45",
               "short_name" : "45",
               "types" : [ "street_number" ]
            }
      ...lines of more json code
      }
...lines of more json code
}

Here is the link with all the lines of the json code: json geomaps

so, how to use that response as a json? like i put it on a variable like that:

var json=xmlhttp.responseText

And then show the variable json as i want like:

json.results.address_components.long_name

I thougt it would be easy but I don't know how to resolve that.

What i want to do it's to put the json.results.address_comp... into a value on a form:

<fieldset>
    <legend>Serveis de geocodificació</legend>

    Latitud:<br><input type="text" id="lat" value="42.3600077"/><br>
    Longitud:<br><input type="text" id="lng" value="1.4579696"/><br>

    <input type="button" value="Veure dades" onclick="primerSelect(document.getElementById('lat').value, document.getElementById('lng').value)"/>
    <input type="button" value="Veure coordenades"/><br>

    Carrer:<br><input type="text" id="car"/><br>
    Ciutat:<br><input type="text" id="ciu"/><br>
    Pais:<br><input type="text" id="pai"/><br>
    CP:<br><input type="text" id="cod"/><br>
    <div id="txtHint"></div>
</fieldset>

Anyone can help?

Upvotes: 4

Views: 21797

Answers (1)

meda
meda

Reputation: 45490

parse the JSON like this

var json = JSON.parse(xmlhttp.responseText);
var results = json.results;
for (var x in results) {
    var address_components = results[x].address_components;
    for (var i in address_components) {
        console.log(address_components[i].long_name);
    }
}

Upvotes: 8

Related Questions