Read and manipulate json data using jquery

Asked

Viewed 32,695 times

1

They say that Json is simple. But I’m in a lot of pain.

Following code:

$(document).ready(function(){
    $.get( "http://meusite.com/", function(data) {
         console.log(data);
    });
});

the result the console.log is

[
    {"id":"769","cidade":"minhacidade","estado":"PR"},
    {"id":"855","cidade":"Caram","estado":"PR"}
]

Exactly what I need. (so far I have) But from that point on, I can’t get out. I need to manipulate these results.Break into pieces.

By in Divs.

But I can’t (I googled all) anything right.

What I have to do so that I can put ex:

  • Print the second city ID on the screen.

  • The second state

And so on because this Json will grow and grow.

  • You can give an example of what HTML should look like?

  • Look, just teaching me how to put a die of this Json in a simple DIV. The rest I do. For example (Id 2) in a DIV. I don’t need anything else

5 answers

8


Man, I know what’s going on. Your return to be coming in string, you have to convert into object to be able to manipulate it.

Observe:

var valorRetornado = '[{"id":"769","cidade":"minhacidade","estado":"PR"},{"id":"855","cidade":"Caram","estado":"PR"}]'
        // convertendo a string em objeto
        var obj = JSON.parse(valorRetornado);

        obj.forEach(function(o, index){
            console.log(o.cidade);
        });

The collaborators gave several examples, but in all of them convert object into string, when in fact you should do the opposite.

  • 1

    True, watching more and learning I realized it. That’s why I changed the way I receive. You’re right. Thanks

  • contribute to my reputation manow, I’m starting now..

5

Friend you have an object in hand. To manipulate the object you use the syntax:

*object[key] ou object.key*

In your case you’ll stay:

console.log( data[0]['id'] );

To insert this data into a DIV or any element, you can do this in N ways. It can be by the CLASS selector or the ID selector, there are other ways to do it, but these are the first ones. You can read the Jquery documentation for more details.

https://api.jquery.com/category/selectors/

Good studies friends.

  • I already did so tbm the result is Undefined

  • A ok friend, put an input before the key, example: date[0]['id'], see what happens.

  • You’re right. But I changed the method instead of $get I used $getJSON Ai worked out console.log(date[1]['city']);

  • 1

    Beauty, now remove the -1 and mark as the best answer hehe

2

In that data you are receiving a JSON. In case it is still on String you can convert to Array. From there it’s simple. An example could be like this:

data = typeof data == 'string' ? JSON.parse(data) : data; // para garantir que o formato é correto
// e depois:
data.forEach(... etc 

Example:

[{
    "id": "769",
    "cidade": "minhacidade",
    "estado": "PR"
}, {
    "id": "855",
    "cidade": "Caram",
    "estado": "PR"
}].forEach(function(elementoDaArray) {
    var div = document.createElement('div'); // criar o elemento
    div.id = elementoDaArray.id; // dar-lhe o ID do objeto
    div.innerHTML = JSON.stringify(elementoDaArray); // dar-lhe conteúdo
    document.body.appendChild(div); // inserir no DOM
});

Example: https://jsfiddle.net/g3gmzk2p/

If you want to use jQuery to do the same it may be so:

$('<div/>', {
    id: elementoDaArray.id,
    html: JSON.stringify(elementoDaArray)
}).appendTo(document.body);

Instead of the $.get you could use the $.getJSON which already gives you a JSON. To iterate the object you receive you can use the data.forEach(function(... like I did on top, or a cycle for.

  • I did it your way and it worked too. Thanks

1

Solved changed the way to call, to $.getJSON .

$.getJSON( "http://meusite.com/", function( data ) {
//console.log(data);

console.log(data[0]['cidade']);
console.log(data[1]['cidade']);

});

This method makes me an obejto (the other a text).

With this I was able to access each index. Com console.log(date[1]['city']);

Worked.

Also with $get worked. So I’ll leave the two ways for whoever needs it.

$(document).ready(function(){
    $.get( "http://meusite.com/", function( data ) {


data = typeof data == 'string' ? JSON.parse(data) : data;
data.forEach(function(elementoDaArray) {

    var div = document.createElement('div');

    id = elementoDaArray.id;
    cidade = elementoDaArray.cidade;
  
    console.log(cidade);
    console.log(id);


    //div.innerHTML = JSON.stringify(elementoDaArray);
    //document.body.appendChild(div);


});

  • Just a tip, it would be very good if you use Success and error, because if there is an error in this call, you can treat the error and print something user friendly. It’s just a hint.

  • Yes I will use it. Thank you

0

$.get is a simplified version of $.ajax, has fewer parameters. To use json one must use ajax, since it has the datatype parameter, which must be set to json.

in this case:

$.ajax({
method:"get",
dataType:"json",
url:"seusite",
success: function(data){
console.log(data["id"]);
}

N

this example I get the id, for others just use date[name].

Hug

  • I tried that tbm but I get it Uncaught Syntaxerror: Unexpected end of input

Browser other questions tagged

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