0

我的控制器文件中有以下函数,其中有一个字符串,我正在尝试使用 JSON.parse 解析它。我面临的问题是我无法打印返回的哈希中存在的消息值。

def index
  .........  
  r = '{"response":"{\"message\":\"The following page was successfully Created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}"}'
  @hash = JSON.parse(r)
  respond_to do |format|
  format.html
  end    
end

在我的视图文件中,我使用以下代码

<%= @hash['response']['message'] %>

我得到的输出是 消息 而不是得到 以下页面已成功创建 3035

我的控制器文件上有“需要 json”。

如果我做

<%= @hash['response'] %>

然后我得到了整个哈希。请帮忙

4

3 回答 3

2

JSON 字符串看起来不正确。它基本上包含一个键/值对,其中键是response,其余的是String包含看起来要转义的 JSON 的内容:

"{\"message\":\"The following page was successfully Created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}"

换句话说,鉴于您提供的输入,您所看到的行为是可以预期的。

如果您将 JSON 输入更改为(即确保 in 中的值response不是作为 JSON 编码的字符串给出):

r = '{"response":{"message":"The following page was successfully Created 3035","success":"0","page_id":"3035"}}'

我想它会像你期望的那样工作。

The reason @hash['response']['message'] is returning "message" is because @hash['response'] is a String. Sending [] to a String with a String parameter results in the parameter String being returned if it occurs in the recipient String:

"foobar"["bar"] #=> "bar"
"foobar"["baz"] #=> nil

See String#[] for the details.

于 2013-10-07T11:02:27.023 回答
0

您似乎为 r 分配了错误的 JSON 字符串。正确的字符串应如下所示:

"{\"response\":{\"message\":\"The following page was successfully Created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}}"

与您的版本相比,它在响应内容周围没有双引号,因此会JSON.parse返回一个具有您期望的正确值的哈希:

{"response"=>{"message"=>"The following page was successfully Created 3035", "success"=>"0", "page_id"=>"3035"}}
于 2013-10-07T11:00:16.213 回答
0

Try this:-

def index
 r = '{"response":"{\"message\":\"The following page was successfully Created 3035\",\"success\":\"0\",\"page_id\":\"3035\"}"}'
 @hash = JSON.parse(r)
 @messagehash= JSON.parse(@hash['response')

 respond_to do |format|
    format.html
 end    
end

In your View:-

 <%= @messagehash['message'] %>
于 2013-10-07T11:07:30.183 回答