I have an object and want to represent it as string with some addtional formatting.
Here is my code:
// stringify object and remove double quotations
let outPut = JSON.stringify(myObject).replace(/"/g, '')
// replace commas with new line character while comma is not part of an array
outPut = outPut.replace(/,/g, '\n') // this line replaces all commas
Since my object contains arrays and I want to preserve commas within the brackets [...]
, I need to tell the replace
function to match only when the comma is not within brackets.
How can I achieve this?
Example input string:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
I need to replace all commas except the ones inside ["GML", "XML"]
.