Josh Spademan
Josh Spademan

Reputation: 113

Append to JSON array via JS

I have the JSON array in the file colors.json

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

and the js addColors.js

function addColor(){
    //code
}

that is run from an html form.

After getting data from by html form, via the js, how would I then append it to the colors.json file?

Thank you Josh

Upvotes: 1

Views: 93

Answers (2)

csharpfolk
csharpfolk

Reputation: 4280

I don't fully understand you question, please provide more info, here is answer that assumes that you want to modify real file on disk.

I assume you are using node.js and colors.js resides on HTTP server and user can submit some data via HTML form that should be added to colors.js.

On server:

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

To add color POST JSON to http://localhost:5000/, GET this address to get current colors.json file. In this case you should use AJAX (e.g. jQuery - ajax) to post form data to server in JSON format.

Upvotes: 0

Cristian Michel
Cristian Michel

Reputation: 326

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

} 

Upvotes: 2

Related Questions