4

Ok, so I am programming a web operating system using js. I am using JSON for the file system. I have looking online for tutorials on JSON stuff for about a week now, but I cannot find anything on writing JSON files from a web page. I need to create new objects in the file, not change existing ones. Here is my code so far:

{"/": {
            "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/": {

                }   
            }
        }}
4

2 回答 2

4

我认为更好的解决方案是将您的 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);
于 2013-06-10T15:21:50.760 回答
0

我会从键中删除“/”,然后可以在“/”上拆分并通过将值从结果中移出来遍历树。例如,以下代码将创建完整路径(如果它不存在),但如果存在则保留文件夹和内容。

var fs = {
    "bin": {
        "mkdir": function(inPath) {
            // Gets rid of the initial empty string due to starting /
            var path = inPath.split("/").slice(1);
            var curFolder = fs;

            while(path.length) {
                curFolder[path[0]] = curFolder[path[0]] || {};
                curFolder = curFolder[path.shift()];
            }
        }
    }
}

fs.bin.mkdir("/foo/bar");

console.log(JSON.stringify(fs, function(key,val) {
    if(key === 'mkdir') return undefined;

    return val;
}, 2));

输出:

{
  "bin": {},
  "foo": {
    "bar": {}
  }
}

正如其他人所提到的,为了避免语法错误(和挫折),而不是使用字符串手动构建 JSON 对象,通过代码构建它然后使用 JSON.stringify 来获得最终结果可能会更简单。

于 2013-06-10T16:30:40.483 回答