javascript - 如何在javascript中写入json文件

标签 javascript json

好的,所以我正在使用 js 编写网络操作系统。我正在为文件系统使用 JSON。我已经在网上寻找关于 JSON 内容的教程大约一个星期了,但是我找不到任何关于从网页编写 JSON 文件的内容。我需要在文件中创建新对象,而不是更改现有对象。到目前为止,这是我的代码:

{"/": {
            "Users/": {
                "Guest/": {
                    "bla.txt": {
                        "content": 
                            "This is a test text file"
                    }

                },
                "Admin/": {
                    "html.html": {
                        "content": 
                            "yo"

                    } 
                }
            },
            "bin/": {
                "ls": {
                        "man": "Lists the contents of a directory a files<br/>Usage: ls"
                },
                "cd": {
                    "man": "Changes your directory<br/>Usage: cd <directory>"
                },
                "fun": {
                    "man": "outputs a word an amount of times<br/>Usage: fun <word> <times>"
                },
                "help": {
                    "man": "shows a list of commands<br/>Usage: help"
                },
                "clear": {
                    "man": "Clears the terminal<br/>Usage: clear"
                },
                "cat": {
                    "man": "prints content of a file<br/>Usage: cat <filename>"
                }
            },
            "usr/": {
                "bin/": {

                }, 
                "dev/": {

                }   
            }
        }}

最佳答案

我认为更好的解决方案是将您的 JSON 字符串化,使用 base64 编码进行编码,然后将其发送到可以保存此文件的服务器端脚本(例如 PHP 页面)。见:

var json = JSON.stringify(myJson);
var encoded = btoa(json);

您可以使用ajax发送:

var xhr = new XMLHttpRequest();
xhr.open('POST','myServerPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send('json=' + encoded);

在服务器端:

$decoded = base64_decode($_POST['json'])
$jsonFile = fopen('myJson.json','w+');
fwrite($jsonFile,$decoded);
fclose($jsonFile);

关于javascript - 如何在javascript中写入json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027101/

相关文章:

javascript 行为 - 函数表达式与函数声明 - 区别

json - 如何使用nodejs和mongo客户端更新保存在mongodb中的记录?

json - 如何在 JSON 文件中翻译 Laravel 的默认验证错误?

javascript - D3.js 生成有效的 SVG 但不显示任何内容

javascript - 获取调用函数的当前元素?

javascript - 在 jquery codeigniter 中上传图像后进行编辑

php - 如何在 script 标签内打印 JSON 数组?

javascript - 我可以一次性将其转换为长度吗?

c# - 如何将 YAML 转换为 JSON?

javascript - 有人可以解释一下 onsubmit 和 action 之间的区别吗?