简体   繁体   English

Ruby - 意外的Hash数据结构

[英]Ruby - Unexpected Hash data structure

A simple question: 一个简单的问题:

In rails I get as response an hash like this: 在rails中我得到像这样的哈希响应:

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

So, the difference from a normal structure I guess is- "new_id": -instead of- new_id: 所以,我认为与正常结构的区别是 - “new_id”: - 而不是new_id:

Does anyone know how to retrieve the data labelled "new_id"? 有谁知道如何检索标记为“new_id”的数据? The usual array["new_id"] doesn't work. 通常的数组[“new_id”]不起作用。

The response to the code: 对代码的响应:

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

is simply: 很简单:

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

I come from the implementation of JSON_response. 我来自JSON_response的实现。 Anyway, they changed the app and I don't have anymore a JSON message, but they use the method: 无论如何,他们改变了应用程序,我不再有JSON消息,但他们使用的方法:

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

More: 更多:

If I write: 如果我写:

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

the answer printed is simply: 印刷的答案很简单:

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

and the request for the :new_id content does not to be received. 并且不会收到对new_id内容的请求。

Much more interesting is the following: After the fact that: 更有趣的是以下内容:事实之后:

puts new_customer_id["new_id"]

prints: 打印:

=> new_id

If I write: 如果我写:

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

I obtain: 我获得:

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

Also: 也:

if I write: 如果我写:

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

I obtain: 我获得:

=> new_
=> new_i

and if I write: 如果我写:

puts new_customer_id["new_id_anyOtherCharacter"]

I get nothing 我一无所获

Luca 卢卡

That's not a ruby object you are getting back. 这不是你要回来的红宝石对象。 It's JSON. 这是JSON。 You can get the new_id in a variety of ways: 您可以通过多种方式获取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]

I bet the hash has a symbol key instead of a string key. 我敢打赌哈希有一个符号键而不是一个字符串键。 Try with array[:new_id] . 尝试使用array[:new_id]

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

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