Doubt with json format Asp.net core web api

Asked

Viewed 124 times

0

Hello

I have a functional example of data query searching the zip, the data are returning in the format:

inserir a descrição da imagem aqui

    function searchCep () {

        // Recupera o value do input cep
        let cep = document.getElementById('cep').value

        // Inicia requisição AJAX com o axios
        axios.get(`http://api.postmon.com.br/v1/cep/${cep}`)
                .then(response => {
                                                console.log(response.data)
                    showResults (response.data)
                })
                .catch(error => {
                    // console.log(error)

                    // Mostra a div com o erro
                    document.getElementById('error').style.display = 'block'

                    // Mostra a mensagem
                    document.getElementById('error').innerHTML = 'Erro inesperado'
                })
                .finally(() => endPreloader ())

        event.preventDefault()
    }


function showResults(registros) {
    console.log(registros)
    console.log(`<p><b>Estado: </b> ${registros.nome} </p>`)

    // Mostra a div com o resultado
    document.getElementById('results').style.display = 'block'

    // Mostra os resultados:
    document.getElementById('results').innerHTML = `
                <p><b>ID: </b> ${dados.id} </p>
                <p><b>Nome: </b> ${dados.nome} </p>
                <p><b>Sexo: </b> ${dados.sexo} </p>
                <p><b>Estado: </b> ${dados.estado} </p>
            `
}

This model works, but if I have data in another format, I cannot capture the information, although they return;

inserir a descrição da imagem aqui

  • If you are returning an array of objects, just make a loop and inside put the function showresults()

  • @Evertonneri, the problem is that in the format it comes [{"id:"3}] as it is coming with [], so I’m not getting the content

  • the first print is returned a "{}" object, the second an "[]" array of "{}" objects is returned, which would be something like this: "[{},{},{} ...]"

1 answer

0


To capture data from an array, I can use: console.log(records[0]. name)

the final example would look like this:

    // Mostra os resultados:
    document.getElementById('results').innerHTML = `
                        <p><b>ID: </b> ${registros[0].id} </p>
                        <p><b>nome: </b> ${registros[0].nome} </p>
                        <p><b>idade: </b> ${registros[0].idade} </p>
                        <p><b>sexo: </b> ${registros[0].sexo} </p>
                        <p><b>Estado: </b> ${registros[0].estado} </p>
                    `

Browser other questions tagged

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