1

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

Mohan Singh
  • 1,142
  • 3
  • 15
  • 30
  • is this frontend or backend variable? so like would you want to create a downloadable file in the browser or prompt the script to save it on the server – Krzysztof Krzeszewski Nov 13 '19 at 10:59
  • Solutions here: https://stackoverflow.com/questions/7346563/loading-local-json-file – BhAvik Gajjar Nov 13 '19 at 11:05
  • "but it seems it doesn't find the file..." — What does that mean? Does the Network tab show a 404 Not Found response? Does the Console show any errors? – Quentin Nov 13 '19 at 11:46

2 Answers2

1

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);
}
cbalakus
  • 620
  • 7
  • 15
0

$.getJSON is asynchronous so you should do:

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