How to get a json value from a string.string

Asked

Viewed 390 times

1

Having a JSON of the type: {"HOME":{"INTRODUCAO":"midias/video1.mp4"}}

How to get the value midia/video1.mp4 from the string

var key = "HOME.INTRODUCAO";

I’ve tried to:

var key = "HOME.INTRODUCAO";     

$.getJSON([CAMINHO DO JSON], function(j){

    alert(j.key);

});

But I get the message "Undefined".

  • Have you tried using JSON.parse()? Ex: j = JSON.parse(j); Alert(j. key);

  • Hello, unfortunately when I try to parse I only get the first letter of the string. But vlw!

  • Hello Paulo! Where does this JSON come from? It is a string yet or object?

  • Hello Sergio, JSON is in a separate file. my variable "key" I get it like this: var key= $("#test"). attr('video');

  • Paul, okay and what gives if fiseres console.log(typeof key, key); after that line you indicated?

  • Hello Sergio, I did like this: var key=$("#test"). attr('video'); console.log(typeof key, key); I got it from the console: "string HOME.INTRODUCTION".

Show 1 more comment

2 answers

2

First, to access properties using a string, if you wear clasps ([]) and not point.

The function getJson returns an object, you only need to do data["HOME"].["INTRODUCAO"] to access this property.

$.getJSON("http://ip.jsontest.com/", function(payload) {
  console.log(payload.ip);
  // ^ Pra mostrar que getJson retorna um objeto
  
  var fakeData = { HOME: { INTRODUCAO: 'midias/video1.mp4' } };
  // ^ é o formato que estará o objeto "data" no teu exemplo

  console.log(fakeData["HOME"]["INTRODUCAO"]);      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Thanks for the suggestion, but I get a "key" variable with the value "HOME.INTRODUCAO" and needed to get the value of json through this variable.

0

I managed to solve my problem as follows:

                        var w = key.split(".");
                        var x = null;                            
                        for (i = 0; i < w.length; i++) { 

                            if(x==null){
                             x = j[w[i]];

                            }else{
                                 x = x[w[i]];
                            }
                        }
Obrigado!

Browser other questions tagged

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