Javascript 如何在本地(在机器上)保存 JSON 数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28464449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:49  来源:igfitidea点击:

How to save JSON data locally (on the machine)?

javascriptjqueryjsonsave

提问by POOJA GUPTA

I am using the following link to create a tree like structure: LINK

我正在使用以下链接创建一个树状结构: LINK

This is my code :

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Tree Context Menu - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="themes/icon.css">
    <link rel="stylesheet" type="text/css" href="demo.css">
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.easyui.min.js"></script>
</head>
<body>
    <h2>Tree Context Menu and Drag Drop Tree Nodes</h2>
    <p>Right click on a node to display context menu.</p>
    <p>Press mouse down and drag a node to another position.</p>
    <div style="margin:20px 0;"></div>
    <div class="easyui-panel" style="padding:5px">
        <ul id="tt" class="easyui-tree" data-options="
                url: 'tree_data1.json',
                method: 'get',
                animate: true,
                dnd:true,
                onContextMenu: function(e,node){
                    e.preventDefault();
                    $(this).tree('select',node.target);
                    $('#mm').menu('show',{
                        left: e.pageX,
                        top: e.pageY
                    });
                }
            ">
        </ul>
    </div>
    <div style="padding:5px 0;">
        <a href="#" class="easyui-linkbutton" onclick="save()" data-options="iconCls:'icon-save'">Save</a>
    </div>
    <div id="mm" class="easyui-menu" style="width:120px;">
        <div onclick="append()" data-options="iconCls:'icon-add'">Append</div>
        <div onclick="removeit()" data-options="iconCls:'icon-remove'">Remove</div>
        <div class="menu-sep"></div>
        <div onclick="expand()">Expand</div>
        <div onclick="collapse()">Collapse</div>
    </div>
    <script type="text/javascript">
        function append(){
            var t = $('#tt');
            var node = t.tree('getSelected');
            t.tree('append', {
                parent: (node?node.target:null),
                data: [{
                    text: 'new item1'
                },{
                    text: 'new item2'
                }]
            });
        }
        function removeit(){
            var node = $('#tt').tree('getSelected');
            $('#tt').tree('remove', node.target);
        }
        function collapse(){
            var node = $('#tt').tree('getSelected');
            $('#tt').tree('collapse',node.target);
        }
        function expand(){
            var node = $('#tt').tree('getSelected');
            $('#tt').tree('expand',node.target);
        }
    function save(){
            var a = document.createElement('a');
        a.setAttribute('href','data:text/plain;charset=utf-u,'+encodeURIComponent(JSON.stringify({$('#tt').html()}));
        a.setAttribute('download', "data.json");

        }
    </script>
</body>
</html>

When I am running this, nothing is getting saved.

当我运行它时,什么也没有得到保存。

I have added a save button to this structure's code.

我在这个结构的代码中添加了一个保存按钮。

I want that whenever the user clicks this save button then he could store this tree structure produced as JSON data on his/her local machine. I want this as this tree is editable. How can I do this?

我希望每当用户点击这个保存按钮时,他就可以在他/她的本地机器上存储这个作为 JSON 数据生成的树结构。我想要这个,因为这棵树是可编辑的。我怎样才能做到这一点?

I used the following link for the same:

我使用了以下链接:

link

关联

I want that whatever changes that happens to the id = "tt" could be retrieved in the form of JSON and store on my local machine.

我希望 id = "tt" 发生的任何更改都可以以 JSON 的形式检索并存储在我的本地机器上。

回答by Dustin Poissant

Sure this can be done.

这当然可以做到。

Once you have your JSON string (Im assuming you know how to get it because if not that's a different question altogether) you can save it using this function:

一旦你有了你的 JSON 字符串(我假设你知道如何获取它,因为如果不是,那完全是一个不同的问题)你可以使用这个函数保存它:

function saveText(text, filename){
  var a = document.createElement('a');
  a.setAttribute('href', 'data:text/plain;charset=utf-8,'+encodeURIComponent(text));
  a.setAttribute('download', filename);
  a.click()
}

Call it:

称它为:

var obj = {a: "Hello", b: "World"};
saveText( JSON.stringify(obj), "filename.json" );

This would prompt the use to save a file named "filename.json", which contains a JSON object of obj

这将提示用户保存一个名为“filename.json”的文件,其中包含一个 JSON 对象 obj

回答by n6g7

LocalStoragedoes exactly that.

LocalStorage正是这样做的。

Use it like this :

像这样使用它:

localStorage.setItem('myCat', 'Tom');
console.log(localStorage.getItem('myCat')); // Tom

Use can use it to store stringify-ed objects as well :

使用也可以使用它来存储stringify-ed 对象:

var obj = { a : 1, b : 2};
localStorage.setItem('myObj', JSON.stringify(obj));
var obj2 = JSON.parse(localStorage.getItem('myObj'));