如何使用 Javascript 将数据写入 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32546100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write data to a JSON file using Javascript
提问by asiacares64
For example, I have a .JSON
file that has the following:
例如,我有一个.JSON
包含以下内容的文件:
[{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}]
What would be the javascript code to push another object {"nissan": "sentra", "color": "green"}
into this .json
array to make the .json
file look like
将另一个对象推{"nissan": "sentra", "color": "green"}
入此.json
数组以使.json
文件看起来像的 javascript 代码是什么
[{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"},{"nissan": "sentra", "color": "green"}]
The reason I'm asking is I am finding a lot of information online on how to pull data from a .json file using AJAX but not writing new data to the .json file using AJAX to update the .json file with additional data.
我问的原因是我在网上找到了很多关于如何使用 AJAX 从 .json 文件中提取数据但不使用 AJAX 将新数据写入 .json 文件以使用其他数据更新 .json 文件的信息。
Any help would be appreciated!
任何帮助,将不胜感激!
采纳答案by asiacares64
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}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
有些人错误地使用术语 JSON 来指代普通的旧 JavaScript 对象,例如[{a: 1}]
. 这恰好是一个数组。如果你想向数组中添加一个新元素,只需添加一个元素push
,如
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
JSON 一词也可用于指代以 JSON 格式编码的字符串:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
请注意(单)引号表示这是一个字符串。如果您有这样的字符串是从某处获得的,则需要首先将其解析为 JavaScript 对象,使用JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
现在您可以以任何您想要的方式操作对象,包括push
如上所示。如果你想把它放回一个 JSON 字符串,那么你可以使用JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
JSON 还用作格式化数据的常用方法,以便将数据传输到服务器或从服务器传输数据,并在服务器上保存(持久化)数据。这就是 ajax 的用武之地。Ajax 用于从服务器获取数据(通常采用 JSON 格式),和/或以 JSON 格式将数据发送到服务器。如果您收到来自 JSON 格式的 ajax 请求的响应,您可能需要JSON.parse
如上所述。然后您可以操作该对象,使用 将其放回 JSON 格式JSON.stringify
,并使用另一个 ajax 调用将数据发送到服务器进行存储或其他操作。
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (nota string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
您使用术语“JSON 文件”。通常,“文件”一词用于指代某个设备上的物理文件(不是您在代码中处理的字符串或 JavaScript 对象)。浏览器无法访问您机器上的物理文件。它无法读取或写入它们。实际上,浏览器甚至没有真正的“文件”的概念。因此,您不能只是在本地机器上读取或写入一些 JSON 文件。如果您正在向服务器发送 JSON 和从服务器发送 JSON,那么当然,服务器可能会将 JSON 存储为文件,但更有可能的是,服务器会根据从数据库中检索到的数据,基于某些 ajax 请求构建 JSON ,或在某些 ajax 请求中解码 JSON,然后将相关数据存储回其数据库。
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
你真的有一个“JSON 文件”,如果有,它在哪里存在,你从哪里得到它?您是否有一个 JSON 格式的字符串,需要对其进行解析、处理并转换回新的 JSON 格式字符串?您是否需要从服务器获取 JSON,并对其进行修改,然后将其发送回服务器?或者您的“JSON 文件”实际上只是一个 JavaScript 对象,您只需要使用普通的 JavaScript 逻辑进行操作?
回答by AnonDCX
JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage
可以使用 JSON.stringify 将 JSON 写入本地存储以序列化 JS 对象。您不能仅使用 JS 写入 JSON 文件。仅 cookie 或本地存储
var obj = {"nissan": "sentra", "color": "green"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
并稍后检索对象
var obj = JSON.parse(localStorage.getItem('myStorage'));
回答by Bharata
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
不幸的是,今天(2018 年 9 月)您找不到用于客户端文件写入的跨浏览器解决方案。
For example:in some browser like a Chrome we have todaythis 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.
例如:在像 Chrome 这样的浏览器中,我们今天有这种可能性,我们可以使用FileSystemFileEntry.createWriter()和客户端调用来编写,但根据文档:
此功能已过时。尽管它可能在某些浏览器中仍然有效,但不鼓励使用它,因为它可以随时被删除。尽量避免使用它。
对于 IE(但不是 MS Edge),我们也可以使用 ActiveX,但这仅适用于该客户端。
If you want update your JSON file cross-browser you have to use server and client side together.
如果你想跨浏览器更新你的 JSON 文件,你必须同时使用服务器端和客户端。
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 FileReadertoo. For the cross-browser writing to the file you have to have some server (see below on server part).
在客户端,您可以向服务器发出请求,然后您必须读取来自服务器的响应。或者您也可以使用FileReader读取文件。对于跨浏览器写入文件,您必须拥有一些服务器(请参阅下面的服务器部分)。
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.
您可以使用很多不同的服务器,但我想写关于 PHP 和 Node.js 服务器的文章。
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.comand for Node.js I would recommend to see and to read this list.
通过使用搜索机器,您可以找到“免费的 PHP 虚拟主机*”或“免费的 Node.js 虚拟主机”。对于 PHP 服务器,我会推荐000webhost.com,对于 Node.js,我会推荐查看和阅读此列表。
PHP server side script solution
PHP服务器端脚本解决方案
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
}
?>
Node.js server side script solution
Node.js 服务器端脚本解决方案
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:
我认为 Node.js 对初学者来说有点复杂。这不像浏览器中的普通 JavaScript。在您开始使用 Node.js 之前,我建议您阅读两本书中的一本书:
The Node.js script for reading and writing from JSON file:
用于从 JSON 文件读取和写入的 Node.js 脚本:
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:
Node.js 的相关链接: