in reply to Regex replacing Brackets with horizontal tabs and newliners
Note that the following does not in any way encode, decode, parse or validate JSON syntax. It just naively pretty-prints JSON-ish stuff that is assumed valid. I'm sure there are modules that would do a much better, more reliable job of this, but you specify that, for some reason, you do not want to use any modules. (Update: Note in particular choroba's comments on this.)
Win8 Strawberry 5.8.9.5 (32) Wed 09/07/2022 7:13:21 C:\@Work\Perl\monks >perl use strict; use warnings; use Data::Dump qw(dd); # for debug my $j = <<'EOJ'; "device": [{"host_info" : { "engine_id":null , "name": null ,"host_group_info" :{"name":null,"remarks":null , "id" : 0 } }} ] EOJ print ">>\n$j<< \n"; my $dent = ' '; my $n_dent = 0; my %pretty = ( '{' => sub { my $d = $dent x ++$n_dent; return qq{$_[0]\n$d}; }, '}' => sub { my $d = $dent x --$n_dent; return qq{\n$d$_[0]}; }, ',' => sub { my $d = $dent x $n_dent; return qq{$_[0]\n$d}; }, ':' => sub { my $d = $dent x $n_dent; return qq{$_[0] }; }, ); $j =~ s{ \s* ([{},:]) \s* } { $pretty{$1}->($1) }xmsge; print ">>\n$j<< \n"; ^Z >> "device": [{"host_info" : { "engine_id":null , "name": null ,"host_group_info" :{"name":null,"remarks":null , "id" : 0 } }} ] << >> "device": [{ "host_info": { "engine_id": null, "name": null, "host_group_info": { "name": null, "remarks": null, "id": 0 } } }] <<
Update: Here's a variation that handles double-quoted strings a little better. All the old caveats still apply.
Win8 Strawberry 5.30.3.1 (64) Wed 09/07/2022 8:14:56 C:\@Work\Perl\monks >perl use 5.010; # needs \K regex extension use strict; use warnings; # use Data::Dump qw(dd); # for debug my $j = <<'EOJ'; "device\"": [{"host_in}fo" : { "eng{ine_id,":null , "name:": null ,"host_group_info\\" :{"na\"me":null,"\"remarks":null , "id" : 0 } "{[:," : "weird", "crazy" : "[{,:" }} ] EOJ print ">>\n$j<< \n"; use constant DENT => ' '; my $n_dent = 0; my %pretty = ( '{' => sub { my $d = DENT x ++$n_dent; return "$_[0]\n$d"; }, '}' => sub { my $d = DENT x --$n_dent; return "\n$d$_[0]\n$d"; }, ',' => sub { my $d = DENT x $n_dent; return "$_[0]\n$d"; }, ':' => sub { my $d = DENT x $n_dent; return "$_[0] "; }, ); my $rx_d_quote = qr{ " [^\\"]* (?: \\. [^\\"]*)* " }xms; $j =~ s{ $rx_d_quote? \K \s* ([{},:]) \s* } { $pretty{$1}->($1) }xmsge; print ">>\n$j<< \n"; ^Z >> "device\"": [{"host_in}fo" : { "eng{ine_id,":null , "name:": null ,"host_group_info\\" :{"na\"me":null,"\"remarks":null , "id" : 0 } "{[:," : "weird", "crazy" : "[{,:" }} ] << >> "device\"": [{ "host_in}fo": { "eng{ine_id,": null, "name:": null, "host_group_info\\": { "na\"me": null, "\"remarks": null, "id": 0 } "{[:,": "weird", "crazy": "[{,:" } } ] <<
Give a man a fish: <%-{-{-{-<
|
---|