【问题标题】:Append to JSON array via JS通过 JS 追加到 JSON 数组
【发布时间】:2016-06-22 20:28:05
【问题描述】:

我在 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文件中?

谢谢 乔什

【问题讨论】:

    标签: javascript html json append


    【解决方案1】:
    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);
    
    } 
    

    【讨论】:

      【解决方案2】:

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

      我假设您使用的是 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)以 JSON 格式将表单数据发布到服务器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-16
        • 2012-06-09
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-13
        相关资源
        最近更新 更多