Write JSON to Javascript object

Asked

Viewed 171 times

1

I have an API in php that returns data like this:

{"status":"sucesso","dados":[{"id":"1","nome":"Nome do Usuario","etc..":"etc.."},{"id":"2","nome":"Nome do Usuario","etc..":"etc.."}]}

I need to read and write 2 of all data (id and name) in an object, but I didn’t understand very well the part of how to write the data, so far I have it:

//Pesquisa o Json

$.getJSON('http://192.168.0.106/teste/SimpleBook/api/v1/Mostrar/Usuarios/', function(data) {
    if (!data.error) {
        var geraldata = data['dados'];

        var data = [];
        for (var i = geraldata.length - 1; i >= 0; i--) {
            data.push ({
                id: data['dados'][i]['id'],
                text: data['dados'][i]['name']
            });
        }
    } else {
        alert(data.msg)
    }
});

The expected result would be something like this:

// Resultado esperado
var data = [{
    id: 0,
    text: 'Nome do Usuario'
}, {
    id: 1,
    text: 'Nome do Usuario'
}];
  • The format of your return is not valid!

  • What would be the correct format for return?

  • 1

    In the format you entered in the question this coming object inside the object { {"id": "01" .... and this is not a valid syntax, the right one would be an array and inside it the objects.

  • Ahnn yes sorry, I just corrected the example.. This part validates, my difficulty is in writing the same data

  • And you want to write where? Database, file, etc. In your script you are already reading (note the name of the attribute "name" which is like "name")

  • I only need to record the return in a variable

Show 1 more comment

2 answers

1

You empty the vector data that contains data coming from your API after passing only the property Dados for another variable. In the loop, the program tries to read the property that no longer exists from the vector data that is empty:

var geraldata = data['dados'];    // Passa somente a propriedade Dados para a outra variável

var data = [];    // Esvazia o vetor que tinha o retorno da API
for (var i = geraldata.length - 1; i >= 0; i--) {
    data.push ({
        id: data['dados'][i]['id'],    // Tenta ler o vetor vazio 
        text: data['dados'][i]['name']
    });
}

Whereas the return of your API is the same indicated, ie the properties are Dados and nome and not dados and name, a solution can be:

var dados_da_api = []

for (var i = data['Dados'].length - 1; i >= 0; i--) {
    dados_da_api.push ({
        id: data['Dados'][i]['id'],     
        text: data['Dados'][i]['nome']
    });
}
  • It worked, thank you very much! I just can’t use the variable out of the if, says it hasn’t been set.. How do I pass the variable data_da_api out of the if?

  • You can declare the variable outside of if that it will be able to be accessed and modified from within if ;)

1


You can use the method map() to map each object and its properties, then just store the values in a array:

let retorno = {"status":"sucesso","dados":[{"id":"1","nome":"Nome do Usuario","etc..":"etc.."},{"id":"2","nome":"Nome do Usuario","etc..":"etc.."}]};

let dadosFormatados = [];

retorno.dados.map(_dados => dadosFormatados.push({
    id: _dados.id,
    nome: _dados.nome
}))

console.log(dadosFormatados)

Browser other questions tagged

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