Chase
Chase

Reputation: 121

how to write json files in javascript

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

                }   
            }
        }}

Upvotes: 4

Views: 25629

Answers (2)

dc5
dc5

Reputation: 12431

I'd take off the "/"'s from the keys then could split on "/" and walk the tree by shifting values off the result. For example, the following code will create the full path if it doesn't already exist, but preserving the folder & contents if it does.

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));

Output:

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

As others have mentioned, rather than building the JSON object by hand with strings, to avoid syntax errors (and frustration), building it through code then using JSON.stringify to get the final result would likely be simpler.

Upvotes: 0

Danilo Valente
Danilo Valente

Reputation: 11352

I think the better solution is to stringify your JSON, encode with base64 encoding and then send it to a server-side script (a PHP page, for instance) which could save this file. See:

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

You can use ajax for sending:

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

And in the server-side:

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

Upvotes: 4

Related Questions