[英]How can I create a hash from json response in perl
我有一個json響應,例如
{
"extId" : "abc:3",
"intId" : "val:0500019141EBE54B",
"type" : "Map"
}{
"extId" : "abc:4",
"intId" : "val:0500012BEA8FEC15",
"type" : "Map"
}{
"extId" : "abc:3",
"intId" : "val:0500019141EBE54B",
"type" : "Map"
}
我想創建一個哈希,例如$hash{abc:3} = val:0500019141EBE54B
,這樣我可以驗證是否為相同的intId
創建了相同的extId
。 感謝幫助。
use Data::Dumper;
my @data = <DATA>;
s/[\r\n\s{}",]//g, s/(ext|int)Id:|type:Map// for @data;
my %hash = grep length, @data;
print Dumper \%hash;
__DATA__
{
"extId" : "abc:3",
"intId" : "val:0500019141EBE54B",
"type" : "Map"
}{
"extId" : "abc:4",
"intId" : "val:0500012BEA8FEC15",
"type" : "Map"
}{
"extId" : "abc:3",
"intId" : "val:0500019141EBE54B",
"type" : "Map"
}
請注意,字段(extId,intId)是必填項。
您尚未發布的不是JSON。 假設您說它來自JSON響應,我將猜測這是一個轉置錯誤。 如果不是這種情況,那就行不通了-但是您應該戳一下給您提供JSON的人員,並告訴他們他們做錯了。
您還應該注意-您請求的哈希-您在intId
有重復的鍵。 因此,如果將其轉換為哈希,將會丟失其中之一。
但是基於以上假設:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $JSON_text = '[
{
"extId" : "abc:3",
"type" : "Map",
"intId" : "val:0500019141EBE54B"
},
{
"intId" : "val:0500012BEA8FEC15",
"type" : "Map",
"extId" : "abc:4"
},
{
"intId" : "val:0500019141EBE54B",
"type" : "Map",
"extId" : "abc:3"
}
]';
#turn JSON into a perl data structure.
#In this case, an array of anon hashes.
my $json_obj = decode_json ( $JSON_text );
print Dumper \$json_obj;
#process that perl data structure, and extract the keys
# use the fact that a list of paired values can be
#assigned to a hash as if they were key-value pairs:
my %int_ext = map { $_ -> {extId},
$_ -> {intId} }
@{$json_obj};
print Dumper \%int_ext;
這使我們的%int_ext
哈希成為:
$VAR1 = {
'abc:3' => 'val:0500019141EBE54B',
'abc:4' => 'val:0500012BEA8FEC15'
};
注意-由於有兩個abc:3
鍵,因此您將“丟失”其中一個。 (第一個被覆蓋,在這種情況下並不重要)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.