简体   繁体   English

"如何使用 Javascript 将数据写入 JSON 文件"

[英]How to write data to a JSON file using Javascript

For example, I have a .JSON<\/code> file that has the following:例如,我有一个.JSON<\/code>文件,其中包含以下内容:

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

You have to be clear on what you mean by "JSON".您必须清楚“JSON”的含义。

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]<\/code> .有些人错误地使用术语 JSON 来指代普通的旧 JavaScript 对象,例如[{a: 1}]<\/code> 。 This one happens to be an array.这个恰好是一个数组。 If you want to add a new element to the array, just push<\/code> it, as in如果你想向数组中添加一个新元素,只需push<\/code>它,如

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

JSON can be written into local storage using the JSON.stringify to serialize a JS object.可以使用 JSON.stringify 将 JSON 写入本地存储以序列化 JS 对象。 You cannot write to a JSON file using only JS.您不能仅使用 JS 写入 JSON 文件。 Only cookies or local storage仅 cookie 或本地存储

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.不幸的是,今天(2018 年 9 月)您找不到用于客户端文件写入的跨浏览器解决方案。

For example:<\/strong> in some browser like a Chrome we have today<\/strong> this possibility and we can write with FileSystemFileEntry.createWriter()<\/a><\/strong> with client side call, but according to the docu:例如:<\/strong>在像 Chrome 这样的浏览器中,我们今天<\/strong>有这种可能性,我们可以使用FileSystemFileEntry.createWriter()<\/a><\/strong>进行客户端调用,但根据文档:

This feature is obsolete.<\/em>此功能已过时。<\/em> Although it may still work in some browsers, its use is discouraged since it could be removed at any time.<\/em>尽管它在某些浏览器中可能仍然有效,但不鼓励使用它,因为它可能随时被删除。<\/em> Try to avoid using it.<\/em>尽量避免使用它。<\/em>


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.对于 IE(但不是 MS Edge),我们也可以使用 ActiveX,但这仅适用于该客户端。

<\/blockquote>

If you want update your JSON file cross-browser you have to use server and client side together.<\/strong>如果要跨浏览器更新 JSON 文件,则必须同时使用服务器端和客户端。<\/strong>

The client side script客户端脚本<\/h2>

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<\/a><\/strong> too.或者您也可以使用FileReader<\/a><\/strong>读取文件。 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);<\/code><\/pre>

Server side scripts服务器端脚本<\/h2>

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.你可以使用很多不同的服务器,但我想写一些关于 PHP 和 Node.js 服务器的文章。

By using searching machine you could find " free PHP Web Hosting<\/a> *" or " free Node.js Web Hosting<\/a> ".通过使用搜索机,您可以找到“免费 PHP Web Hosting<\/a> *”或“ 免费 Node.js Web Hosting<\/a> ”。 For PHP server I would recommend 000webhost.com<\/a> and for Node.js I would recommend to see and to read this list<\/a> .对于 PHP 服务器,我推荐000webhost.com<\/a> ,对于 Node.js,我推荐查看并阅读此列表<\/a>。

PHP server side script solution<\/strong> PHP服务器端脚本解决方案<\/strong>

The PHP script for reading and writing from JSON file:用于读取和写入 JSON 文件的 PHP 脚本:

 <?php \/\/ This PHP script must be in "SOME_PATH\/jsonFile\/index.php" $file = 'jsonFile.txt'; if($_SERVER['REQUEST_METHOD'] === 'POST') \/\/ or if(!empty($_POST)) { file_put_contents($file, $_POST["jsonTxt"]); \/\/may be some error handeling if you want } else if($_SERVER['REQUEST_METHOD'] === 'GET') \/\/ or else if(!empty($_GET)) { echo file_get_contents($file); \/\/may be some error handeling if you want } ?><\/code><\/pre> 
                      

Node.js server side script solution<\/strong> Node.js 服务端脚本解决方案<\/strong>

I think that Node.js is a little bit complex for beginner.我认为 Node.js 对于初学者来说有点复杂。 This is not normal JavaScript like in browser.这与浏览器中的普通 JavaScript 不同。 Before you start with Node.js I would recommend to read one from two books:在开始使用 Node.js 之前,我建议您阅读两本书中的一本:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM