无法读取perl中的json文本:将数组强制转换为哈希时的错误索引

时间:2014-05-08 11:05:29

标签: arrays json perl

我有json字符串:

[{"oslc_cm:totalCount":1,"oslc_cm:results":[{"rtc_cm:photo":null,"rtc_cm:modifiedBy":{"rdf:resource":"https:\/\/xyz.com\/jts\/users\/abc"},"dc:modified":"2014-03-27T11:25:55.504Z","rdf:resource":"https:\/\/xyz.com\/jts\/users\/user","rtc_cm:userId":"id","rtc_cm:emailAddress":"mailto:abc%40xyz.com","dc:title":"JSON Editor"}]}]

尝试读取代码dc:title的值 但得到错误 在

处将数组强制转换为哈希时的错误索引

我的代码段就像:

my $json_obj = $json->decode($json_text);
foreach my $item( @{$json_obj} ){
  $WICommentCreator = $item->{'oslc_cm:results'}->{'dc:title'};
}

回答赞赏

1 个答案:

答案 0 :(得分:1)

尝试

$WICommentCreator = $item->{'oslc_cm:results'}[0]{'dc:title'};

而不是

$WICommentCreator = $item->{'oslc_cm:results'}->{'dc:title'};

因为oslc_cm:results是对象/哈希数组,而不是哈希本身。

[
    {
        "oslc_cm:totalCount": 1,
        "oslc_cm:results": [           # array here
            {                          # first element of array
                "rtc_cm:photo": null,
                "rtc_cm:modifiedBy": {
                    "rdf:resource": "https://xyz.com/jts/users/abc"
                },
                "dc:modified": "2014-03-27T11:25:55.504Z",
                "rdf:resource": "https://xyz.com/jts/users/user",
                "rtc_cm:userId": "id",
                "rtc_cm:emailAddress": "mailto:abc%40xyz.com",
                "dc:title": "JSON Editor"   # wanted key/value
            }
        ]
    }
]