将JSON数据保存在本地文件中

时间:2017-07-24 09:54:23

标签: javascript jquery

在我的计划中,我使用JSON获得JSON.stringify()格式数据。现在我想将这个JSON对象保存在文件中。

我的问题是:当点击JSON上的按钮时,如何将jquery数据保存在本地创建的文件中?

我的JSON对象是这样的:

{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}

3 个答案:

答案 0 :(得分:1)

twFile检查这个jquery插件。

允许您读取和写入本地文件。

我希望这可以帮到你

答案 1 :(得分:1)

您可以使用Blob构造函数和URL.createObjectURL()创建一个临时锚标记,其download属性设置为可下载文件应具有的名称,然后触发{{1该锚元素上的事件。遗憾的是,这不适用于任何浏览器,但对Blob constructor的支持实际上非常好。

这是一个例子。

click
var data = '{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}';


document
.querySelector('#download')
.addEventListener('click', function() {

  var blob = new Blob( [ data ], {
      type: 'application/octet-stream'
  });

  var url = URL.createObjectURL( blob );
  var link = document.createElement( 'a' );
  link.setAttribute( 'href', url );
  link.setAttribute( 'download', 'data.json' );

  link.click()

  URL.revokeObjectURL(url)

})

答案 2 :(得分:0)

使用localStorage!这就像Cookies,但文件可能更大:

var json = '{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}';


localStorage.setItem("json", json);

// if you want to use it, simply use localStorage.getItem("json")

console.log(JSON.parse(localStorage.getItem("json")));