简体   繁体   English

如何读取本地 json 文件并将其存储在变量中?

[英]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.在我的脚本中,我有一个 Json 存储在一个变量中。 I Would like to store the json in a local file.我想将 json 存储在本地文件中。 (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此致

if you want to use local file, you need to use FileReader.如果要使用本地文件,则需要使用 FileReader。 Which mean is you need to select manually your json file.这意味着您需要手动 select 您的 json 文件。

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.并且您需要将 json 作为字符串下载。 And here is download json code:这里是下载 json 代码:

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);
}

$.getJSON is asynchronous so you should do: $.getJSON 是异步的,所以你应该这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM