Consume json file locally with jquery or javascript

Asked

Viewed 117 times

-1

I have a json called product.json that is at the root of my project, I want to consume it and put it in a showcase at home, but I tried several ways and could not, follows example:

$(document).ready(function(){
    $.get( "product.json", function(data) {
         console.log(data);
    });
});

2 answers

0

First, try modifying "$(Document). ready(" for "$().ready("

Then replacing .get( for .ajax(

$().ready(function(){
    console.log('Start');
    $.ajax({
                type: "POST",
                dataType: "json",
                url: "https://gameinfo.albiononline.com/api/gameinfo/battles?offset=0&limit=1&sort=recent", 
                success: function(data) {
                         console.log('vai'+data);
                },
                fail: function() {
                         console.log('data');
                }
    });
    console.log('End');
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

0

The problem is that the method $.get receives JSON in string form, and would need to parse the return data with JSON.parse(data), but jQuery has a method that already does this, the $.getJSON():

$(document).ready(function(){
    $.getJSON( "product.json", function(data) {
         console.log(data);
    });
});

Thus the value in data will be parsed JSON, from where you can consume the information you want.

Browser other questions tagged

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