I found a workaround for errors parsing JSON strings sent from (Firefox) browser using JSON.parse() in my controller, but isn’t there a better solution?
rails 2.3.12
json (1.6.1)
View –> Controller
views/theme_maps/edit.html.erb:
(javascript)
var labels = ["4", "5"];
document.getElementById("labels").value = JSON.stringify(labels);
(html)
<% form_for(@theme_map}) do |f| %>
<input type="hidden" id='labels' name='labels' />
<%= f.submit 'Update' %>
<% end %>
theme_maps_controller#update:
(ruby)
labels = params[:labels] # get it from the hidden field
the problem, and my hack solution, is here:
# labels.inspect returns: "\"[\\\"4\\\", \\\"5\\\"]\""
# JSON.parse(labels) throws an exception.
labels.gsub!('"[', '[') # remove the quotes
labels.gsub!(']"', ']') # around the brackets.
labels.gsub!('\\', '') # remove the escaped backslash.
# now labels.inspect returns: "[\"4\", \"5\"]"
labels_array = JSON.parse(labels)
# now it's happy.
Controller –> View
Just to round things out, and because it took me ages to figure this out:
theme_maps_controller#edit:
(ruby)
label_list = ["1", "2","3"]
@json_labels = label_list.to_json
views/theme_maps/edit.html.erb:
(javascript)
var exist_labels = <%= @json_labels %>;
The problem is using
JSON.stringify(). What is needed is.toSource().