how to append comma inbetween json file in cypress

93 Views Asked by At

my write file : cy.writeFile("cypress/fixtures/xlsxData.json", Newdata , { flag: 'a+' })

Newdata - let Newdata = { FirstName:F_jsonData[i][0], MiddleName:F_jsonData[i][1], LastName:F_jsonData[i][2] }

and xlsxdata.json will be:

 [ {
  "FirstName": "ABC",
  "MiddleName": "K",
  "LastName": "edf"
}{
  "FirstName": "sss",
  "MiddleName": "g",
  "LastName": "efg"
} ] 

How can I add comma between 2 objects in the json file?

2

There are 2 best solutions below

5
Rachel.Zawadi On

It's a mistake to use {flag:'a+'}, that's only useful for text-like, for example logs, which take a stream of lines.

Instead, let javascript append the structure correctly (applies to any objects, not just this one).

const filePath = 'cypress/fixtures/xlsxData.json'
cy.readFile(filePath).then(data => {
  data.push(Newdata)
  cy.writeFile(filePath, data)   // write back the expanded data
})
2
Anthony Turpel On

If you want a comma, there is nothing stopping you from writing a comma.

const filePath = 'cypress/fixtures/xlsxData.json'
cy.writeFile(filePath, ', ', { flag: 'a+' })
cy.writeFile(filePath, Newdata , { flag: 'a+' })