Search JSON format information from a url

Asked

Viewed 872 times

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 take this information and put it in a string?

  • This topic can help you: http://stackoverflow.com/questions/9838812/how-can-i-open-a-json-file-in-javascript-without-jquery

  • To put in a string you can use JSON.stringify(): JSON.stringify( json ), being json the person whose or a variable containing any valid.

  • This url seems to be already in string.... how are you accessing this url? via ajax or opening the page directly? you can put the url in question?

1 answer

3

First 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 usually used to allow communication between a system (can be a page) and the server.

For example, in order for a page to read this content, it is necessary for it 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 how to turn JSON into a string. in this case the xmlhttp.responseText is already the text you are looking for.

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

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

Once you have recovered the json, you will be able to 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 above case the list of people, when we found 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 method JSON.stringify

var serializedJSON = JSON.stringify(json);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.