【问题标题】:Not able to read json text in perl : Bad index while coercing array into hash无法在 perl 中读取 json 文本:将数组强制转换为哈希时索引错误
【发布时间】:2014-06-25 17:45:06
【问题描述】:

我有 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处的值 但得到错误为 在

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

我的代码 sn-p 是这样的:

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

感谢回答

【问题讨论】:

    标签: arrays json perl


    【解决方案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
                }
            ]
        }
    ]
    

    【讨论】:

    • 我怎样才能使这个动态,我的意思是当数组大小不只是 0 时。
    • @user3616128 循环遍历 @{$item->{'oslc_cm:results'}} 数组,就像您对 @{$json_obj} 所做的那样。
    • @user3616128 如果它适合你,你可以接受答案。
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多