繁体   English   中英

Ruby - 意外的Hash数据结构

[英]Ruby - Unexpected Hash data structure

一个简单的问题:

在rails中我得到像这样的哈希响应:

{"success":true,"new_id":816704027}

所以,我认为与正常结构的区别是 - “new_id”: - 而不是new_id:

有谁知道如何检索标记为“new_id”的数据? 通常的数组[“new_id”]不起作用。

对代码的响应:

new_customer_id = @response.body
puts new_customer_id
puts new_customer_id["new_id"]

很简单:

=> {"success":true,"new_id":816704028}
=> new_id

我来自JSON_response的实现。 无论如何,他们改变了应用程序,我不再有JSON消息,但他们使用的方法:

return_200(additional_items: {:new_id => "@customer.id"} )

更多:

如果我写:

new_customer_id = @response.body
puts new_customer_id
puts new_customer_id[:new_id]

印刷的答案很简单:

=> {"success":true,"new_id":816704028}

并且不会收到对new_id内容的请求。

更有趣的是以下内容:事实之后:

puts new_customer_id["new_id"]

打印:

=> new_id

如果我写:

puts new_customer_id["new_id"][0]
puts new_customer_id["new_id"][1]
puts new_customer_id["new_id"][2]
...

我获得:

=> n
=> e
=> w
...

也:

如果我写:

puts new_customer_id["new_"]
puts new_customer_id["new_i"]

我获得:

=> new_
=> new_i

如果我写:

puts new_customer_id["new_id_anyOtherCharacter"]

我一无所获

卢卡

这不是你要回来的红宝石对象。 这是JSON。 您可以通过多种方式获取new_id:

JSON.parse(@response.body)["new_id"]

JSON.parse(@response.body).symbolize_keys[:new_id]

JSON.parse(@response.body).with_indifferent_access[:new_id]

使用params来获得如下值:

new_id= array[:new_id]

我敢打赌哈希有一个符号键而不是一个字符串键。 尝试使用array[:new_id]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM