title: Parsing JSON data from Ruby variable
body: <p>I'm using an external API to pull information from another site.  I have the valid JSON stored in an instance variable called @result.  However, passing it to the view, JavaScript doesn't recognize that it is JSON.  </p>
  
  <p>I have tried the following: </p>
  
  <pre><code>var data = JSON.stringify('&lt;%= @result %&gt;');
  var apiData = JSON.parse(data);
  </code></pre>
  
  <p>Where the structure of @result is this: </p>
  
  <pre><code>[{"name"=&gt;"VONDERSAAR, FRANK J", "fec_id"=&gt;"H4AK00057", "pcc"=&gt;"C00503896", "party"=&gt;"D", "candidate_url"=&gt;"/candidate/2014/vondersaar-frank-j/H4AK00057/", "race_url"=&gt;"/race/2014/H/AK/00/", "ie_url"=&gt;"/outside-spending/#?ordering=-expenditure_date_formatted&amp;candidate_id_checked=H4AK00057", "is_incumbent"=&gt;false, "cycle"=&gt;"2014", "not_seeking_reelection"=&gt;false, "other_office_sought"=&gt;nil, "other_fec_id"=&gt;nil, "election_year"=&gt;2014, "state"=&gt;"AK", "office"=&gt;"H", "office_district"=&gt;"00", "term_class"=&gt;nil, "candidate_status"=&gt;"LP", "total_expenditures"=&gt;"0.00", "expenditures_supporting"=&gt;"0.00", "expenditures_opposing"=&gt;"0.00", "total_receipts"=&gt;"500.00", "total_contributions"=&gt;"0.00", "total_disbursements"=&gt;"400.00", "cash_on_hand"=&gt;"100.00", "cash_on_hand_date"=&gt;"2014-07-31", "district"=&gt;{"race_name"=&gt;"2014 AK-00 (House)", "state"=&gt;"AK", "office"=&gt;"H", "office_district"=&gt;"00", "term_class"=&gt;nil, "id"=&gt;541}, "outstanding_loans"=&gt;"500.00", "cand_is_gen_winner"=&gt;false, "status"=&gt;"Lost in primary"}]
  </code></pre>
  
  <p>If I attempt to access the "name" attribute via:</p>
  
  <pre><code>console.log(apiData[0]["name"]);
  </code></pre>
  
  <p>It gives me </p>
  
  <pre><code>undefined
  </code></pre>
  
  <p>Another attempt:</p>
  
  <pre><code>var apiData = JSON.parse("&lt;%= @result %&gt;");
  </code></pre>
  
  <p>This gives me:</p>
  
  <pre><code>Uncaught SyntaxError: missing ) after argument list
  </code></pre>
  
  <p>I have also tried escaping "" but haven't gotten the syntax right.<br>
  I know the JSON is valid because I'm using it fine with the rest of my application.  It's the handing off to JavaScript that is the problem. It treats it as a string and won't parse it correctly. </p>
  
  <p><strong>Edit</strong></p>
  
  <p>I should add that in my controller I am already parsing the api_result into JSON via Ruby.</p>
  
  <pre><code>api_result = [api call]
  base       = JSON.parse(api_result)
  @result    = base["results"]
  </code></pre>
  
  <p><strong>Solution</strong></p>
  
  <p>I got it to work with the following. 
  Controller:</p>
  
  <pre><code>api_result = [raw request]
  @result    = api_result.to_json 
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>var apiData = &lt;%= @result.to_json %&gt;;
  </code></pre>
  
  <p>Thanks for the help everyone.  </p>