how to access json?

2

I think the simplest thing is to access a key and a value in json, but for weeks I'm not able to do that ... it returns json right through ajax but when I try to access it does not. Note: I am a layman and I am learning.

follow 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);

    }); }

Obs2: when I was passing html direct I did not give this error but then I was told that it is not viable and functional to do so I changed to ajax with json. Thanks any help

    
asked by anonymous 31.08.2016 / 07:38

1 answer

2

JSON has two methods :

  • stringify , to transform an object with Primitives into a String
  • parse , to transform a String into JSON format into an object

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

However you could use $.getJSON and simplify things:

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