title: Passing Values Back and Forth from Browser to Controller Using JSON
body: <p>I found a workaround for errors parsing JSON strings sent from (Firefox) browser using <code>JSON.parse()</code> in my controller, but isn't there a better solution?  </p>
  
  <p>rails 2.3.12<br>
  json (1.6.1) &nbsp;&nbsp; </p>
  
  <hr>
  
  <h2>View --> Controller</h2>
  
  <hr>
  
  <p><code>views/theme_maps/edit.html.erb</code>:  </p>
  
  <p>(javascript)</p>
  
  <pre><code>var labels = ["4", "5"];
  document.getElementById("labels").value = JSON.stringify(labels);
  </code></pre>
  
  <p>(html)</p>
  
  <pre><code>&lt;% form_for(@theme_map}) do |f| %&gt;  
  &lt;input type="hidden" id='labels' name='labels' /&gt;  
  &lt;%= f.submit 'Update' %&gt;  
  &lt;% end %&gt;  
  </code></pre>
  
  <hr>
  
  <p><code>theme_maps_controller#update</code>:  </p>
  
  <p>(ruby) </p>
  
  <pre><code>  labels = params[:labels]     # get it from the hidden field  
  </code></pre>
  
  <h2>the problem, and my hack solution, is here:</h2>
  
  <pre><code>  #   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. 
  </code></pre>
  
  <hr>
  
  <h2>Controller --> View</h2>
  
  <hr>
  
  <p>Just to round things out, and because it took me ages to figure this out:  </p>
  
  <p><code>theme_maps_controller#edit</code>:<br>
  (ruby)</p>
  
  <pre><code>  label_list = ["1", "2","3"]
    @json_labels = label_list.to_json  
  </code></pre>
  
  <hr>
  
  <p><code>views/theme_maps/edit.html.erb</code>:  </p>
  
  <p>(javascript)</p>
  
  <pre><code>  var exist_labels = &lt;%= @json_labels %&gt;;
  </code></pre>