Get #Amazon #Prime for this #holiday #amazonprime #christmas #2019

How to use #Nodejs to read, process and write #JSON files? #JavaScript

You can use Node to process your JSON files locally.
Use Node File System API readFileSync to read a JSON file and writeFile to write the output.
Before writing to a file, use JSON stringify to JS Object to a JSON string.

// processJSON.js

var args = process.argv; // parse argument when the file is being executed
var inputFile = args[2] || './input.json';
var fs = require('fs');
var inputData;

inputData = JSON.parse(fs.readFileSync(inputFile, 'utf8'));

// process data
for (var i = 0; i < inputData.length; i++) {
    inputData[i].index = i;
}

fs.writeFile('./output.json', JSON.stringify(inputData, null, 2), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log('Data has been processed');
});

// input.json

[
  {
    "item": "article1",
    "title": "title1"
  },
  {
    "item": "article2",
    "title": "title2"
  },
  {
    "item": "article3",
    "title": "title3"
  }
]

Run node processJSON.js to process a JSON file. The argument variable is not needed as long as you name your input file as input.json.

Nodejs execute file
Nodejs execute file

Result:


vim output.json 

Output.JSON
Output.JSON

Thank you for reading!

Jun