[英]Perl loop within regex match
Take a look at this command:看看这个命令:
perl -0777ne 'print "$&\n\n" while /"(QueryString|Params)":\[(\{"Name":".*?", ?"Value":".*?"\},? ?)*\]/g;' myfile.json
It iterate through each match of json strings like:它遍历每个匹配的 json 字符串,例如:
{
"Some": "Random stuff",
"QueryString": [
{ "Name": "IsOrdered", "Value": "1" },
{ "Name": "TimeStamp", "Value": "11654116426247" }
],
"Params": [
{ "Name": "ClassName", "Value": "PRODUCT" },
{ "Name": "ListID", "Value": "Products" },
{ "Name": "Mode ", "Value": "1" },
{ "Name": "Dept" , "Value": "5" },
{ "Name": "HasPrevOrder", "Value": "" }
],
"And": {
"QueryString":[]
},
"More": "like",
"More+": "this"
}
Now my question is how to iterate through each regex match of the Name/Value pairs, and join them together back to normal http query string?现在我的问题是如何遍历名称/值对的每个正则表达式匹配,并将它们连接在一起回到正常的 http 查询字符串?
For .eg, For例如,对于
"QueryString":[{"Name":"IsOrdered", "Value":"1"}, {"Name":"TimeStamp", "Value":"11654116426247"}]
the joined output should be连接的输出应该是
"QueryString":"IsOrdered=1&TimeStamp=11654116363378"
and "QueryString":[]
to "QueryString":""
和
"QueryString":[]
到"QueryString":""
Note that I want to do regex match & replace because I need the rest of the JSON components be preserved.请注意,我想做正则表达式匹配和替换,因为我需要保留其余的 JSON 组件。 The JSON file I'm talking about is actually a har file.
我说的 JSON 文件实际上是一个har文件。 It's quit a complicated structure, yet
它不再是一个复杂的结构,但
"(QueryString|Params)":\[(\{"Name":".*?", ?"Value":".*?"\},? ?)*\]
is all that I want to replace.是我想要替换的所有东西。 Nothing more.
而已。
I'd use jq
.我会使用
jq
。
jq '
walk(
if type == "object" then
(
( .QueryString, .Params ) | select( . != null )
) |= (
map( @uri "\( .Name )=\( .Value )" ) | join("&")
)
else
.
end
)
'
This modifies all object with elements with one of those keys.这会修改所有具有这些键之一的元素的对象。 I usually prefer something more targeted (not just for efficiency reasons, but to avoid accidentally changing something that shouldn't be changed), but I don't have enough knowledge of the HAR format to do this.
我通常更喜欢更有针对性的东西(不仅仅是出于效率原因,而是为了避免意外更改不应更改的内容),但我对 HAR 格式的了解不足,无法做到这一点。
The following is a Perl program that would also achieve the task:以下是一个也可以完成任务的 Perl 程序:
use feature qw( say );
use Cpanel::JSON::XS qw( decode_json encode_json );
use URI::Escape qw( uri_escape_utf8 );
sub transform {
for ( @_ ) {
$_ =
join "&",
map {
join "=",
map uri_escape_utf8( $_ ),
$_->@{qw( Name Value )}
}
@$_;
}
}
sub fix {
my $x = shift;
my $type = ref( $x );
if ( $type eq "HASH" ) {
for my $k ( keys( %$x ) ) {
for my $v ( $x->{ $k } ) {
if ( $k eq "QueryString" || $k eq "Params" ) {
transform( $v );
} else {
fix( $v );
}
}
}
}
elsif ( $type eq "ARRAY" ) {
fix( $_ ) for @$x;
}
}
local $/;
while ( <> ) {
my $data = decode_json( $_ );
fix( $data );
say( encode_json( $data ) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.