user3616128
user3616128

Reputation: 377

Not able to read json text in perl : Bad index while coercing array into hash

I have json string as :

[{"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"}]}]

Trying to read value at tag dc:title But getting the error as Bad index while coercing array into hash at

My code snippet is like:

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

answers appreciated

Upvotes: 0

Views: 106

Answers (1)

mpapec
mpapec

Reputation: 50647

Try

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

instead of

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

as oslc_cm:results is array of objects/hashes, not hash itself.

[
    {
        "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
            }
        ]
    }
]

Upvotes: 1

Related Questions