2016-03-08 59 views
1

JSON陣列I具有在文件colors.json附加到經由JS

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

JSON數組和從一個html形式運行的js addColors.js

function addColor(){ 
    //code 
} 

從html表單獲取數據後,如何通過js將其附加到colors.json文件中?

謝謝 喬希

回答

2
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); 

} 
0

我不完全理解你的問題,請提供更多的信息,這裏是回答假設你要修改磁盤上的真實文件。

我假設你正在使用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格式將表單數據發佈到服務器。