5

How to append an existing JSON file with comma "," as separator

anchors = [ {  "title":"  2.0 Wireless " }  ]
fs.appendFileSync('testOutput.json', JSON.stringify(anchors));

This current code's output is like this

[
   {
     "title":"  2.0 Wireless "
   }
 ]
 [
   {
     "title":"  Marshall Major II "
   }
]

How to I get this in the correct format with comma "," as separator

I want to get something like this

[
   {    
    "title":"  2.0 Wireless "
   },
   {
     "title":"  Marshall Major II "
   }
]
Tcmxc
  • 481
  • 1
  • 7
  • 23
  • How about `require()`ing the file, adjusting the JavaScript object structure and writing it to the file again? Note: Even if there would be a `,` between the two arrays in your first example, it wouldn't be valid JSON. Keeping something valid JSON by just appending stuff is not really possible – Capricorn Jun 07 '18 at 18:06
  • I don’t think it would be valid JSON. You could create an array of arrays or an object containing a few arrays. – jens Jun 07 '18 at 18:07
  • If you will append to the file a lot, csv might be a better choice than JSON. With JSON you have to read the whole file every time you edit it. – Xuezheng Ma Jun 07 '18 at 18:14

2 Answers2

5

Try this. Don't forget to define anchors array.

var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);

fs.writeFile("testOutput.json", JSON.stringify(json))
gregnr
  • 1,222
  • 8
  • 11
muco
  • 74
  • 6
  • This almost works my out put looks like this [ { "title":" 2.0 Wireless " }, [{ "title":" Marshall Major II " }] ] – Tcmxc Jun 07 '18 at 18:44
0

I created two small functions to handle the data to append.

  1. the first function will: read data and convert JSON-string to JSON-array
  2. then we add the new data to the JSON-array
  3. we convert JSON-array to JSON-string and write it to the file

example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,

it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.

data = {  "title":"  2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )

the full code is here :

   const fs = require('fs');
   data = {  "title":"  2.0 Wireless " }
   file_path = './my_data.json'
   append_data (file_path , data )

   async function append_data (filename , data ) {

    if (fs.existsSync(filename)) {
        read_data = await readFile(filename)
        if (read_data == false) {
            console.log('not able to read file')
        }
        else {
            read_data.push(data)
            dataWrittenStatus = await writeFile(filename, read_data)
            if dataWrittenStatus == true {
              console.log('data added successfully')
            }
           else{
              console.log('data adding failed')
            }
        }
      else{
          dataWrittenStatus = await writeFile(filename, [data])
          if dataWrittenStatus == true {
              console.log('data added successfully')
          }
          else{
             console.log('data adding failed')
           }
      }
   }



    async function readFile  (filePath) {
      try {
        const data = await fs.promises.readFile(filePath, 'utf8')
        return JSON.parse(data)
      }
     catch(err) {
         return false;
      }
    }

    async function writeFile  (filename ,writedata) {
      try {
          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
          return true
      }
      catch(err) {
          return false
      }
    }
subhadip pahari
  • 799
  • 1
  • 7
  • 16