I have a Ruby hash which is passed to a hidden field. How do I extract this hash into JavaScript arrays that I can work with? I need to access the key/value pairs in JavaScript.
2 Answers
Ruby code:
state = { 'Waiting' => { name: 'Waiting now', color: 'btn-default' },
'Trying' => { name: 'Trying now', color: 'btn-danger' },
'Answered' => { name: 'Answered now', color: 'btn-success' } }
javascript code:
var state = JSON.parse('#{raw(state.to_json)}');
1 Comment
Chip Roberson
Note, the single quotes are important because the to_json method creates a JSON string with embedded double quotes. Here is the form I used in my situation, where the javascript was in an embedded Ruby file (filename.html.erb):
var data = JSON.parse('<%= raw(@contacts_list.to_json) %>');Use my_awesome_ruby_hash.to_json and then you can simply either eval it in js or use parseJSON. You might need to require 'json' (not in Rails).
11 Comments
newbie_86
thanks, that works. how would i iterate through the result in the js code? i.e. the key/value pairs...does json return a js hash?
Jakub Hampl
{ "a" => [1,2,3] } will turn into { "a" : [1,2,3]} so you can do obj["a"] in js to get it or a for in loop.newbie_86
@jakub Hampl - i have this: myList = Hash.new() myList[var1] = const1 myList[var2] = const2 I set a variable in my controller as follows: @myHash = myList.to_json In my javascript, I get the value as follows: theList = JSON.parse($('#hiddenfield').attr('value')); for (key in theList) { alert("key "+key); alert(theList[key]); alert(theList[thelist(key)]); } Alert1 is "key0", Alert2 is "var1", Alert3 is "undefined". I can't seem to access the value per key. Any suggestions?
Jakub Hampl
for (key in object) { if (!object.hasOwnProperty(key)) continue; value = object[key]; } should do the trick.newbie_86
it still doesn't work, just returns the index e.g. 0 and the var1 as above
|