I can not read this JSON

0

This is a .json file that I created just to understand

{
    "campo":
        [
            {"nome":"Lucas vidotti"}

        ]
}

I know that to read this value with jquery I need to do $.getJSON and manipulate by key, but I can not read json and play in html

    
asked by anonymous 27.11.2018 / 21:02

2 answers

2

In parts, concepts to take into account:

  • $.getJSON is asynchronous , you can not just var x = $.getJSON;
  • The API is $.getJSON(<endereço>, callback); , that is, this function consumes the address and then executes the callback when the answer returns
  • callback receives as function argument the result, ie JSON

So what you are looking for is:

$("#mos").click(function(){
  $.getJSON("main.json",function(json){
    const campo = json.campo;
    const nome = campo[0].nome;
    console.log(nome); // deve dar "Lucas vidotti"
  });
});
    
27.11.2018 / 22:24
0

var json = {
    "campo":
        [
            {"nome":"Lucas vidotti"}

        ]
}

$("#mos").click(function(){
    let quem = json.campo[0].nome;
    $( "#resultado" ).html( quem );
});
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonid="mos">mostra</button>

<div id="resultado"></div>
    
27.11.2018 / 23:15