I can’t read this JSON

Asked

Viewed 126 times

0

This is a. json file 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’m not able to read the json and play in html

  • For the structure, it would be something like this: let val = $.getJSON; val.campo[0].nome;

  • 1

    I don’t know how you get json, but if it’s in that structure, that’s the syntax for reading. . to access object key and [indice] to access the array item.

  • You need to pass the file .json for the reading to be made

  • I watched some tutorials and tried to do so $(Function(){ $("#mos"). click(Function(){ $.getJSON("main.json",Function(){ $("#span"). html(field.name); // so here I need to put the field[0]. name? }); }); });

  • @Lucas depends on how you are working, with callback, synchronous, etc

  • if a reply serves you mark it as accepted, see https://i.stack.Imgur.com/jx7Ts.png and why https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079. Enjoy a tour in https://answall.com/tour

Show 1 more comment

2 answers

2

Parts, concepts to be taken into account:

  • $.getJSON is asynchronous, you can’t just do 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
  • to callback takes as argument of the function the result, ie the JSON

So what you seek 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"
  });
});
  • thank you very much helped me a lot !

  • Hi @Lulus! My intention is to solve the problem completely and not "just help" at all:) Still have questions or parts that you don’t understand related to this post? You made it work?

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>
<button id="mos">mostra</button>

<div id="resultado"></div>

  • Thank you very much helped me a lot !!!

Browser other questions tagged

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