Read a Json object with javascript

Asked

Viewed 706 times

0

In a requisicao ajax it returns me the following:

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

My requisica:

$.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 javascript afterwards?

  • Thiago, could be more specific and post your ajax request ?

  • I edited the question!

  • Thank you, I will reply

  • Actually that ain’t a array as the title says, it is an object.

3 answers

1

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

An example would be 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);
}

0

To avoid the problem of [:] we can make a .replace string and recover to 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);

0

To access " Attributes " of ajax return is simple, you just need to put a variable in parentheses ( json ) 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 message status/message, to access these attributes, I use json.status/json.message.

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

Browser other questions tagged

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