Reading a Json object with javascript

0

In an ajax request it returns the following:

{
 "og:locale":"pt_BR",
 "og:type":"article",
 "og:title":"Um titulo qualquer",
 "og:url":"http:\/\/www.umsite.com.br\/uma-url\/"
}

My request:

$.ajax({
            type: "GET",            
            url: '../pegaurl.php',
            data : { "url" : url},
            dataType: 'json',
            success: function (e) {  

                console.info(e[0]);
...

How do I read each element separately in the javascript afterwards?

    
asked by anonymous 01.07.2017 / 17:08

3 answers

1

You can iterate the keys of this object with a for ..in or Object.keys and then forEach or for .

An example would look like this:

var obj = {
  "og:locale": "pt_BR",
  "og:type": "article",
  "og:title": "Um titulo qualquer",
  "og:url": "http:\/\/www.umsite.com.br\/uma-url\/"
};

for (var chave in obj) {
var detalhes = [chave, chave.split(':')[1], obj[chave]].join(' > ');
  console.log(detalhes);
}
    
01.07.2017 / 19:50
0

To access "Attributes" from the ajax return is simple, you just need to put a variable in the parentheses ( json ) of the method used, and access with .nomeAtributo . Example:

$.ajax({
      url: url,
      type: "POST",
      data: dados,
      dataType: "json",
      success: function(json){
        if (json.status) {
          console.log("success");
          $("#cadastrar").each(function() {
            this.reset();
          });

          iziToast.success({
            title: 'Ok',
            message: json.message,
            icon: "zmdi zmdi-thumb-up"
          });

        } else {
          console.log("error");
          iziToast.error({
            title: 'Erro',
            message: json.message,
            icon: "zmdi zmdi-thumb-down"
          });

        }
      },
      error: function(json){
        iziToast.error({
          title: 'Erro',
          message: "Erro ao fazer requisição",
          icon: "zmdi zmdi-thumb-down"
        });
      }
    });

This is an ajax request, and my ajax returns a json with a status and a status/message message, to access those attributes, I use json.status/json.message .

In your case it would be e.locale or e.org:locale

    
01.07.2017 / 18:00
0

To avoid the problem of [ : ] we can make a .replace global string and retrieve for the simple name:

var string = '{"og:locale":"pt_BR","og:type":"article","og:title":"Um titulo qualquer","og:url":"http:\/\/www.umsite.com.br\/uma-url\/"}';
var obj = JSON.parse(string.replace(/og:/g,""));

console.log(obj.locale);
console.log(obj.type);
console.log(obj.title);
console.log(obj.url);
    
26.12.2018 / 20:17