通过 JS 附加到 JSON 数组

Append to JSON array via JS

我在文件 colors.json

中有 JSON 数组
{
"colors": [
    {"RGB": "100, 33, 93","HEX": "Computer Science"},
    {"RGB": "33, 82, 100","HEX": "#55d1ff"},
    {"RGB": "32, 56, 11","HEX": "#518e1d"}
   ]
}

和 js addColors.js

function addColor(){
    //code
}

即 运行 来自 html 表格。

通过 js 从 html 表单获取数据后,如何将其附加到 colors.json 文件?

谢谢 乔什

var json = {

"colors": [
    {"RGB": "100, 33, 93","HEX": "Computer Science"},
    {"RGB": "33, 82, 100","HEX": "#55d1ff"},
    {"RGB": "32, 56, 11","HEX": "#518e1d"}
   ]

}
// example: newValue = {"RGB": "100, 33, 93","HEX": "#518e1X"}
function addColor(newValue) {    

json.colors.push(newValue);

} 

我不完全理解你的问题,请提供更多信息,这里是假设你想修改磁盘上的真实文件的答案。

我假设您正在使用 node.js 并且 colors.js 驻留在 HTTP 服务器上,用户可以通过 HTML 表单提交一些数据,这些数据应该添加到 colors.js

在服务器上:

var fs = require("fs");
var express = require("express");
var app = express();
var bodyParser = require('body-parser');

function addColor(newColor) {
    // Get content from file
    var contents = fs.readFileSync("colors.json");

    // Define to JSON type
    var jsonContent = JSON.parse(contents);

    // Add new color
    jsonContent.colors.push(newColor);

    // Save file to disk
    fs.writeFileSync("colors.json", JSON.stringify(jsonContent));
}

 app.use(bodyParser.json());

 /* serves main page */
 app.get("/", function(req, res) {
    res.sendfile('colors.json');
 });

 app.post("/", function(req, res) {
    // Add color to file
    addColor(req.body);

    res.send("OK");
 });

 var port = process.env.PORT || 5000;
 app.listen(port, function() {
   console.log("Listening on " + port);
 });

要将颜色 POST JSON 添加到 http://localhost:5000/,请获取此地址以获取当前 colors.json 文件。在这种情况下,您应该使用 AJAX(例如 jQuery - ajax)以 post 将数据以 JSON 格式发送到服务器。