How to access json?

Asked

Viewed 395 times

2

I think the simplest thing is to access a key and a value in json, but for weeks I haven’t been able to do it... it returns the correct json through ajax but when I try to access it from. Note: I am half layman and I am learning.

follows code:

function getjson(){
console.log('Recuperando post');
$.post("sistema/getpost.php", 'get',
    function(post){
        // aqui é a cagada que estou fazendo (quando tiro o stringify ele nem aparece)
        var obj = JSON.stringify(post);

        var cont = obj.conteudo;
        var color = obj.cor;
        var like = obj.curtidas;
        var follow = obj.follow;
        var situacao = obj.situacao;

        // esse é o card onde contera os dados
        var posthtml = '<section class=" animated slideInLeft section--center mdl-cell mdl-cell--12-col mdl-cell--6-col--phone mdl-grid demo-card-wide mdl-card mdl-grid--no-spacing" style="margin-bottom:20px; background-color:'+color+';"><div class="demo-card-wide mdl-card mdl-shadow--2dp" style="margin-top:0px; min-height:150px; width:100%; background-color:'+color+';"><div class="mdl-card__title mdl-card--expand" style=" width:100%;"><h4 style="text-align:center; margin-top:30px; background-color:'+color+';">'+cont+'</h4></div><div class="mdl-card__actions mdl-card--border"><div class="quem"><p>'+follow+'</p></div><div class="mdl-layout-spacer"></div><button class="mdl-button mdl-button--colored "><i class="material-icons" style="margin-top:0px; font-size:24px;">chat_bubble</i><span>523</span></button><button class="mdl-button mdl-button--colored " ><i class="material-icons" style="margin-top:0px; font-size:24px;">favorite</i><span>'+like+'</span></button></div></div></section>';

        // aqui é em qual das paginas ele colocara o card
        $( "#tab-1" ).append(posthtml);

    }); }

Provando que ele ta retornando Json..

Obs2: when I was passing html straight I did not give this error but then I was told that it is not feasible and not functional to do it then I switched to ajax with json. I appreciate any help

  • Is not stringify but yes parse...

1 answer

2


The JSON has two methods:

  • stringify, to transform an object with Primitive in a String
  • parse, to transform a String format JSON in an object

So what you should use is .parse() and not .stringify() because the server returns a String JSON and not an object.

Yet you could use $.getJSON and you simplify it:

$.getJSON('sistema/getpost.php', 'get', function(obj){
    var cont = obj.conteudo;
    // etc...

Browser other questions tagged

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