Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX remove whitespace from JSON ignoring values

Tags:

json

regex

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+(?=(?:[^"]*"[^"]*"[^"]*)*$)*(?=(?:[^[]*[[^[]*][^]]*)*$)*

like image 868
Craig Avatar asked Oct 22 '25 00:10

Craig


1 Answers

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]}

RegEx Demo

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.

like image 77
anubhava Avatar answered Oct 25 '25 04:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!