Ruby-如何访问已解析的json中的键值

时间:2019-03-16 23:47:48

标签: ruby-on-rails json ruby parsing

我收到此json作为对我的api调用的响应。我需要获得评论以在测试中进行验证。我只会在响应中得到一条记录。如何访问注释值“意大利食谱”? 我做了JSON.parse(response)并得到了ruby哈希。我需要从哈希中提取值的帮助。

{  
   “recipe”:{  
      "id":10,
      "created_at":"2019-03-16T22:21:03Z",
      "updated_at":"2019-03-16T23:07:07Z",
        },
   "audit":{  
      "id":402216837440,
      "recipe_id":10,
      "created_at":"2019-03-16T23:07:07Z",
       "events":[  
         {  
            "id":402216837460,
            "author_id":179,
            "Comment":"Italian Recipes.",
            "audit_id":402216837440
         }
      ],
      "via":{  
         "channel":"api"
         }
   }
}

我尝试过这种方法,但是我认为这不是正确的格式。我出错了。需要有关正确语法的帮助。

parsed_response = JSON.parse(res)
parsed_response['audit']['events']['comment']

1 个答案:

答案 0 :(得分:2)

json_data = JSON.parse(json_string)
comment = json_data['audit']['events'].first['Comment']
recipe_id = json_data['recipe']['id']