[英]Finding a value in HTTP response content using Perl Script
我有帶有HTTP GET請求的perl腳本。 我的回復內容就像
$VAR1 = \'{"ResultSet": {
"result": [
{
"rank": "999999",
"term": "shampoo"
},
{
"rank": "999999",
"term": "Beauty",
"url": "/search/results.jsp?Ntt=shampoo&N=359434"
},
{
"rank": "999999",
"term": "Baby, Kids & Toys",
"url": "/search/results.jsp?Ntt=shampoo&N=359449"
},
我需要以上響應的url屬性,我該如何獲取它。 使用正則表達式進行迭代,例如my $content =~ m/:"url": "(...)"/;
〜m my $content =~ m/:"url": "(...)"/;
但我沒有得到url值。 請指導。
那就是JSON。 因此,請使用JSON
模塊進行解析:
use JSON;
my $json = decode_json ( $response -> content );
foreach my $element ( @{ $json -> {ResultSet} -> {results} } ) {
print $element -> {url},"\n";
}
更飽; 可運行的示例:
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $json_str = '{
"ResultSet": {
"result": [
{
"rank": "999999",
"term": "shampoo"
},
{
"rank": "999999",
"term": "Beauty",
"url": "/search/results.jsp?Ntt=shampoo&N=359434"
},
{
"rank": "999999",
"term": "Baby, Kids & Toys",
"url": "/search/results.jsp?Ntt=shampoo&N=359449"
}
]
}}';
my $json = decode_json($json_str);
print Dumper $json;
foreach my $element ( @{ $json->{ResultSet}->{result} } ) {
print $element ->{url}, "\n" if $element->{url};
}
在上面, $json_str
填補了內容的利基。 我假設您有純文本,並且上面的輸出是print Dumper \\$content
。
因此打印:
$VAR1 = {
'ResultSet' => {
'result' => [
{
'rank' => '999999',
'term' => 'shampoo'
},
{
'rank' => '999999',
'term' => 'Beauty',
'url' => '/search/results.jsp?Ntt=shampoo&N=359434'
},
{
'url' => '/search/results.jsp?Ntt=shampoo&N=359449',
'term' => 'Baby, Kids & Toys',
'rank' => '999999'
}
]
}
};
/search/results.jsp?Ntt=shampoo&N=359434
/search/results.jsp?Ntt=shampoo&N=359449
您有一個JSON字符串的引用。
首先,獲取JSON。
my $json = $$content;
如果您(錯誤地)執行了Dumper(\\$content)
而不是Dumper($content)
,則忽略上述Dumper($content)
,而使用以下內容:
my $json = $content; # Or just use $content where you see $json later.
然后,使用JSON解析來獲取數據。
use JSON::XS qw( decode_json );
my $data = decode_json($json); # If the $json is UTF-8 (probably)
-or-
use JSON::XS qw( );
my $data = JSON::XS->new->decode($json); # If the $json is decoded (Unicode Code Points)
現在,輕松獲取數據。
my $results = $data->{ResultSet}{result};
for my $result (@$results) {
my $url = $result->{url}
or next;
print("$url\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.