How to get a value from a json from a string.string

1

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

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

var key = "HOME.INTRODUCAO";

I've tried:

var key = "HOME.INTRODUCAO";     

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

    alert(j.key);

});

But I get the message "undefined".

    
asked by anonymous 10.12.2016 / 23:13

2 answers

2

First, to access properties using a string , use brackets ( [] ) instead of point.

The function getJson returns an object, you only need to 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>
    
10.12.2016 / 23:52
0

I was able 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!
    
13.12.2016 / 02:57