How to write data to a JSON file using Javascript

前端 未结 3 678
天命终不由人
天命终不由人 2020-11-28 06:22

For example, I have a .JSON file that has the following:

[{\"honda\": \"accord\", \"color\": \"red\"},{\"ford\": \"focus\", \"color\": \"black\"         


        
3条回答
  •  鱼传尺愫
    2020-11-28 07:00

    Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

    For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

    This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


    For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

    If you want update your JSON file cross-browser you have to use server and client side together.

    The client side script

    On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

    var xhr = new XMLHttpRequest(),
        jsonArr,
        method = "GET",
        jsonRequestURL = "SOME_PATH/jsonFile/";
    
    xhr.open(method, jsonRequestURL, true);
    xhr.onreadystatechange = function()
    {
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            // we convert your JSON into JavaScript object
            jsonArr = JSON.parse(xhr.responseText);
    
            // we add new value:
            jsonArr.push({"nissan": "sentra", "color": "green"});
    
            // we send with new request the updated JSON file to the server:
            xhr.open("POST", jsonRequestURL, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // if you want to handle the POST response write (in this case you do not need it):
            // xhr.onreadystatechange = function(){ /* handle POST response */ };
            xhr.send("jsonTxt="+JSON.stringify(jsonArr));
            // but on this place you have to have a server for write updated JSON to the file
        }
    };
    xhr.send(null);
    

    Server side scripts

    You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

    By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

    PHP server side script solution

    The PHP script for reading and writing from JSON file:

    
    

    Node.js server side script solution

    I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

    • Learning Node: Moving to the Server-Side
    • Node.js Web Development: Server-side development

    The Node.js script for reading and writing from JSON file:

    var http = require("http"),
        fs = require("fs"),
        port = 8080,
        pathToJSONFile = '/SOME_PATH/jsonFile.txt';
    
    http.createServer(function(request, response)
    {
        if(request.method == 'GET')
        {
            response.writeHead(200, {"Content-Type": "application/json"});
            response.write(fs.readFile(pathToJSONFile, 'utf8'));
            response.end();
        }
        else if(request.method == 'POST')
        {
            var body = [];
    
            request.on('data', function(chunk)
            {
                body.push(chunk);
            });
    
            request.on('end', function()
            {
                body = Buffer.concat(body).toString();
                var myJSONdata = body.split("=")[1];
                fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
            });
        }
    }).listen(port);
    

    Related links for Node.js:

    • How to Develop Web Application using pure Node.js (HTTP GET and POST, HTTP Server) (detailed video tutorial)
    • Anatomy of an HTTP Transaction
    • How to handle POST request in Node.js
    • How do you extract POST data in Node.js?

提交回复
热议问题