上载并使用JSON文件 [英] Uploading a JSON file and using it

查看:53
本文介绍了上载并使用JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的网页上单击导入"按钮时上载JSON文件,然后将其存储在变量中,以使用JavaScript进行更新.

How can I upload a JSON file on some click on a button on my web page say "import", and use it to store in a variable to use and update it using JavaScript.

我浏览了其他帖子,但找不到任何答案.

I have gone through the other posts but could not find any answer.

我正在使用此函数保存JSON变量:

I am saving the JSON variable using this function:

function save(filename, data){

    if(!data) {
        alert('error : No data')
        return;
    }

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }

这工作正常,单击另一个按钮,即导出",它下载了文件.如何上传回该文件并为此文件数据创建JSON变量?

This is working fine and it downloads the file on clicking another button say "export". How upload this file back and make a JSON variable of this file data?

推荐答案

没有服务器端代码,您最好的方法可能是为用户提供 textarea 元素,以将JSON复制/粘贴到其中,然后使用 JSON.parse 对其进行解析.

Without server side code, your best approach may be to provide a textarea element for the user to copy/paste the JSON into, and then parse it using JSON.parse.

您甚至可以使用 Ace编辑器之类的东西来为JSON提供语法高亮显示-您可以在 Ace Editor Kitchen Sink演示上查看实际操作-从下拉列表中选择JSON在左上角列出.

You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.

结果证明我错了.这是一个小提琴,展示了正在使用的FileReader,这正是您所需要的:

Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:

https://jsfiddle.net/Ln37kqc0/

这是代码:

Javascript:

document.getElementById('import').onclick = function() {
    var files = document.getElementById('selectFiles').files;
  console.log(files);
  if (files.length <= 0) {
    return false;
  }

  var fr = new FileReader();

  fr.onload = function(e) { 
  console.log(e);
    var result = JSON.parse(e.target.result);
    var formatted = JSON.stringify(result, null, 2);
        document.getElementById('result').value = formatted;
  }

  fr.readAsText(files.item(0));
};

HTML:

<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result"></textarea>

这篇关于上载并使用JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆