Ruby - Unexpected Hash data structure

Simple question:

In rails I get as a response a hash like this:

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

      

So the difference in normal structure I think is "new_id": instead of pointer new_id:

Does anyone know how to get data labeled "new_id"? The regular array ["new_id"] doesn't work.

Answer to code:

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

      

just:

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

      

I am coming from the JSON_response implementation. Anyway, they changed the application and I don't have the JSON message anymore, but they use the method:

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

      

More details:

If I write:

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

      

the answer is printed simply:

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

      

and request to get content: new_id is not accepted.

The following is much more interesting: After 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 get:

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

      

also:

if i write:

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

      

I get:

=> new_
=> new_i

      

and if i write:

puts new_customer_id["new_id_anyOtherCharacter"]

      

I get nothing

Luke

+3


source to share


3 answers


It is not the ruby ​​object you are returning. This is JSON. You can get new_id in various ways:

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



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

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

+2


source


use parameters to get the value like:



new_id= array[:new_id]

      

0


source


I'm pretty sure the hash has a character key instead of a string key. Try it array[:new_id]

.

0


source







All Articles