etienne sigwald
etienne sigwald

Reputation: 21

How to read a local json file and store it in variable?

here is my issue. In my script I have a Json store in a variable. I Would like to store the json in a local file. (it will be a database like, i do this because i would like a standalone and easy to use website without too much component.)

Now, i have this

var data = [{
        "id": 1,
        "oeuvre": "choppe",
        "type": "Objet d'art",
        "artist": "Etienne",
        "sheet": "<a href=\"desc.html\">fiche</a>",
        "dt": "01/01/2019"
      }, {
        "id": 2,
        "oeuvre": "montre",
        "type": "Orfèvrerie",
        "artist": "Etienne",
        "sheet": "<a href=\"desc.html\">fiche</a>",
        "dt": "01/01/2019"
      }]

I would like something like this :

var data = $.getJSON("json/data1.json")

but it seems it doesn't find the file...

Someone have an idea ?

Thanks in advance

Best regards

Upvotes: 1

Views: 634

Answers (2)

cbalakus
cbalakus

Reputation: 630

if you want to use local file, you need to use FileReader. Which mean is you need to select manually your json file.

function readJsonFromLocal() {
    var file = document.getElementById("file");
    var fr = new FileReader();
    fr.readAsDataURL(file.files[0]);
    fr.onloadend = function (event) {    
        var strJson = atob(event.target.result.substring(event.target.result.indexOf("base64,") + 7));
        var jsonObj = JSON.parse(strJson);
    }
}

and you need to download your json as string. And here is download json code:

function downloadJsonFile() {
    var a = $("</a>");
    var url = URL.createObjectURL(new Blob([JSON.stringify(jsonObj)], { type: 'text/json' }));
    $(a).attr("download", "System.json").attr("href", url);
}

Upvotes: 1

BhAvik Gajjar
BhAvik Gajjar

Reputation: 458

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

Upvotes: 0

Related Questions