RE: How to remove whitespaces and newlines from every value in a JSON file?
I want to do the opposite, and ignore values or groups but remove all whitespace from the structure of a JSON, for example:
Input:
{
"1": "This is a string",
"AnInt": 123,
"3": [6, 9, 429]
}
Goal Output:
{"1":"This is a string","AnInt":123,"3":[6,9,429]}
I can get close with
\s (?=(?:[^"]*"[^"]*"[^"]*)*$)
but it does't remove the spaces in and around the group in 3
When I modify the REGEX to capture around the square brackets for groups it breaks completely \s (?=(?:[^"]*"[^"]*"[^"]*)*$)*(?=(?:[^[]*[[^[]*][^]]*)*$)*
CodePudding user response:
You may use this regex to match whitespaces outside quotes:
\s (?=(?:(?:[^"]*"){2})*[^"]*$)
If using a regex engine with support of possessive quantifier:
\s (?=(?:(?:[^"]*"){2})*[^"]* $)
Output:
{"1":"This is a string","AnInt":123,"3":[6,9,429]}
Replacement would be just an empty string.
This regex will split on whitespaces if those are outside double quotes by using a lookahead to make sure there are even number of quotes after matching 1 whitespaces.
CodePudding user response:
You can achieve it in two steps.
First, remove all line breaks
\n
https://regex101.com/r/zxoT1g/1
Second, remove all spaces
({|"|,)([ ]{2,})