从哈希中获取价值

时间:2016-03-10 20:07:46

标签: ruby

我正在编写一个Ruby脚本来抓取App Store的评论。我已经提出了要求并取回了我需要的所有信息。它以以下格式返回:

{
"userReviewList": [{
    "userReviewId": "userID",
    "body": actual_review,
    "date": "2016-03-09T15:10:00Z",
    "name": "Laurean C",
    "rating": 5,
    "title": "Best banking app on my phone!",
    "voteCount": 0,
    "voteSum": 0,
    "viewUsersUserReviewsUrl": "https://itunes.apple.com/us/reviews?userProfileId=profileID",
    "voteUrl": "https://userpub.itunes.apple.com/WebObjects/MZUserPublishing.woa/wa/rateUserReview?userReviewId=appID",
    "reportConcernUrl": "https://userpub.itunes.apple.com/WebObjects/MZUserPublishing.woa/wa/reportAConcernSubmit?cc=us",
    "reportConcernExplanation": "Provide more details about this review of 'app name'. The author of the review will not be able to see this report.",
    "customerType": "Customers",
    "reportConcernReasons": [{
        "reasonId": "0",
        "name": "Choose One"
    }, {
        "reasonId": "1",
        "name": "This review contains offensive material"
    }, {
        "reasonId": "8",
        "name": "This review is not a review or is off-topic"
    }, {
        "reasonId": "9",
        "name": "I disagree with this review."
    }, {
        "reasonId": "7",
        "name": "My concern isn't listed here."
    }]
}, ...

这是一个很大的列表,所以我只包括一个评论的样子。响应以字符串形式返回,在调用JSON.parse(rawResponse.body)后,我有一个名为response的变量,其中应包含数据。

当我打印出response.class时,我被告知它是一个哈希,所以我尝试了以下内容来获取实际数据:

puts response[:userReviewList]

key = 'userReviewList'
puts response[key.to_sym]

这两个都没有返回。我是否做错了以获得哈希值?我正在使用gem rest-client,如果这有任何区别的话。

2 个答案:

答案 0 :(得分:1)

JSON键变为简单的字符串:

// ...

答案 1 :(得分:0)

看起来键是字符串。您可以使用以下方式获取值:

puts response['userReviewList']

或者如果您使用的是Rails:

response.symbolize_keys!
puts response[:userReviewList]