N.B: This question is being asked purely for learning purposes. I am well aware that the specific problem posed can be trivially solved in any modern code editor.
I love the power of regular expressions, but have never quite understood how to use their more-advanced features, especially lookarounds. After two hours of SO searching and Googling, plus using regexr.com, I have come up with the following:
// Search regex: (?<=\[\n *\{\n)(?<= {4})(.*\n)*
// Replace regex: [{\n$&]
// Should take the following JSON object array:
[
{
"prop1": val1,
"prop2": val2,
// ...arbitrary number of props
},
// ...arbitrary number of objects matching the above structure
]
And format it like so:
[{ // first object's opening brace adjacent to opening bracket
// ...first object's props
}, {
// ...other objects' props
}] // last object's closing brace adjacent to closing bracket
The second lookbehind is an attempt to deindent each prop line, and the lines that close each object and open the next one. But it seems to break the whole thing.
Without it I get almost a perfect result, but the lines are not deindented and the newline after the final object's closing brace is also erroneously matched, like so (see the link for a more complete example):
[{
"prop1": val1,
"prop2: val2
}, {
"prop1": val1,
"prop2: val2
}
]
For your specific input, you can delete all matches of
/^ |(?<=\[)[ \n]*(?=\{)|(?<=\})[ \n]*(?=\])/gm
See RegExr link. Alternatively, replace all matches of
/^ |(\[)[ \n]*(\{)|(\})[ \n]*(\])/gm
by $1$2$3$4.
But that only works if the input is formatted exactly as shown in your question, and if the strings (keys or values) do not contain {. "Power of regular expressions" is a good keyword, as classical regexes lack the power to process arbitrarily nested braces. They are not designed to process Type II grammars like JSON.