2

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"].

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 2
    Have you tried [the third parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Parameters) of `JSON.stringify`? – Ram Oct 13 '18 at 11:26
  • @undefined: AFAIK `Space` is used to indent with spaces, but I need some sort of `regex` I guess. –  Oct 13 '18 at 11:51
  • 1
    Just like regex should not be used to match HTML it should not be used to match JSON. JSON like HTML is a tree like data structure and regex is not suitable for matching it. – Krisztián Balla Oct 13 '18 at 12:28
  • Yes, RegEx is a fragile option here. What is the point of doing this after all? – Ram Oct 13 '18 at 12:33
  • @JennyO'Reilly: Thanks for edit. –  Oct 13 '18 at 12:36

1 Answers1

4

You could use the following regex to match commas not in arrays:

(,)(?![^[]*\])

(Explanation on regex101.)

This says to match any comma which, if it is followed by a close bracket, has an opening bracket before that close bracket.


Example in JS:

outPut = outPut.replace(/(,)(?![^[]*\])/g, '\n');

gives:

"{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}}}}}"
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54