简体   繁体   中英

Conversion of a javascript object to a ruby hash

In my existing ruby on rails application, I have a JavaScript object (hash) in one of my view file. The hash needs to be submitted back to the controller during form submission. I have converted the hash to JSON using JSON.stringify(hash_name) method. But it produces a string and I can get the string which looks like the hash in my controller. My purpose was not that. I need to dereference the hash in controller , so that I can save the dereferenced values into database.

My hash looks like as following when I am printing it in controller:

{"Bearing":[["Jeekay",0],["Ecodrive",0]],"Civil":[["Nirlon",0],["SKF",0]],"Compressor":[["Jeekay",0],["Ecodrive",0],["SKF",0]]} 

And it should be like it but not the string.

I have a hidden field in my view. I am putting the hash to the value of the hidden field and submitting the form as

$("#javascript_data").val(JSON.stringify(ultimate_hash));

In my controller I am getting the data as:

check_data=params[:javascript_data]

But check_data is a string.

But since its a string,my purpose was not solved. Please help me by giving some suggestions about how to pass the JavaScript hash to the controller as it is.

Thanks in advance!

You need to parse JSON to get hash. Here:

str = '{"Bearing":[["Jeekay",0],["Ecodrive",0]],"Civil":[["Nirlon",0],["SKF",0]],"Compressor":[["Jeekay",0],["Ecodrive",0],["SKF",0]]}'
JSON.parse str
# => {"Bearing"=>[["Jeekay", 0], ["Ecodrive", 0]], "Civil"=>[["Nirlon", 0], ["SKF", 0]], "Compressor"=>[["Jeekay", 0], ["Ecodrive", 0], ["SKF", 0]]}

or as per your example, simply:

check_data = JSON.parse(params[:javascript_data])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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