Looking for information in JSON format from a url

0

I have a url that when opened has the following json :

[ 
    { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" },
    { "Name" : "Berglunds snabbköp", "City" : "Luleå", "Country" : "Sweden" },
    { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" },     
    { "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, 
    { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid", "Country" : "Spain" }, 
    { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" } 
]

How can I get this information and put it in a string?

    
asked by anonymous 20.03.2015 / 12:42

1 answer

2

First of all, welcome to Stackoverflow. As I see you have no experience with JavaScript, I would like to touch on certain aspects. The first is that this type of page (content) is normally used to allow communication between a system (can be a page) and the server.

For example, for a page to be able to read this content, it needs to make an AJAX request.

var url = "<URL com o seu JSON>";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var json = JSON.parse(xmlhttp.responseText);
        //você poderá acessar o seu objeto aqui.
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

I know your question was about turning JSON into a string. in this case the actual xmlhttp.responseText is already the text you are looking for.

But it does not make sense to work with a JSON in this way, so I believe that what you are looking for is a way to manipulate JSON, in this case the best thing to do is to deserialize the string in an Object, JSON.parse .

var json = JSON.parse(xmlhttp.responseText);

Once you retrieve json, you can navigate through it. for example, if you want to know the name of the Austrian person.

var name;
var contador = json.length;
for (var indice = 0; indice < contador; indice++) {
    var item = json[indice];
    if (item.Country == "Austria") {
        name = item.Name;
        break;
    }
}
console.log(name);

In the case above the list of people, when we find one that belonged to Austria, we interrupt search.

But if you already have a JSON object and need to serialize it as text, you can use the JSON.stringify

var serializedJSON = JSON.stringify(json);
    
20.03.2015 / 14:37