Passing a JSON object from a Rails controller to Javascript

After creating a hash structure in Ruby like this:

Track_list = {:track1=>{:url=>"https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e", :name=>"Demons"},
 :track2=>{:url=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", :name=>"Shots - Broiler Remix"},
 :track3=>{:url=>"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB", :name=>"Radioactive"},
 :track4=>{:url=>"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8", :name=>"Blank Space/Stand By Me - Medley / Live From Spotify London"},
 :track5=>{:url=>"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp", :name=>"Radioactive"}}

I attempted to convert this hash into JSON format for use in my JavaScript file by executing the following code in my controller:

@tl = track_list.as_json
# The resulting JSON output looks like this:
# {"track1"=>{"url"=>"https://open.spotify.com/track /2Oehrcv4Kov0SuIgWyQY9e", "name"=>"Demons"},
# "track2"=>{"url"=>"https://open.spotify.com/track/0z8yrlXSjnI29Rv30RssNI", "name"=>"Shots - Broiler Remix"},
# "track3"=>{"url"=>"https://open.spotify.com/track/6Ep6BzIOB9tz3P4sWqiiAB", "name"=>"Radioactive"},
# "track4"=>{"url"=>"https://open.spotify.com/track/3I05foFixB2sSZvV5Ppty8", "name"=>"Blank Space/Stand By Me - Medley / Live From Spotify London"},
# "track5"=>{"url"=>"https://open.spotify.com/track/4G8gkOterJn0Ywt6uhqbhp", "name"=>"Radioactive"}}

However, upon attempting to print out the JSON object in my JS file, I encountered an issue where quotes were not correctly escaped:

console.log("<%= @tl %>");
"{&quot;track1&quot;:{&quot;url&quot;:&quot;https://open.spotify.com/track/2Oehrcv4Kov0SuIgWyQY9e&quot;,&quot;name&quot;:&quot;Demons&quot;} ..."

Subsequently, when attempting to parse the string to JSON using `JSON.parse`, it did not work and trying to use `JSON.generate` also did not resolve the issue of unescaped quotes.

If anyone has a solution to this problem, your guidance would be greatly appreciated. Thank you!

Answer №1

If you want to pass JSON data from your Rails controller to JavaScript, you can achieve it like this:

console.log("<%= @tl.to_json.html_safe %>");

Answer №2

Consider giving this a try:

let myData = <%= j @tl %>;
console.log(myData);

You have encountered a couple of minor issues in your code. You should make sure to utilize escape_javascript in your view (or its alias j). Additionally, avoid enclosing the JSON object in quotes as it will be interpreted as a string by the browser instead of a JSON object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...

What are some effective methods for handling error objects in REST API services?

Encountered an error object: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) Type of (err): Object Now, I am looking to pass this object to another web service (REST API) What content ty ...

The lack of functionality for lockOrientation in Cordova is causing issues

Currently working with Cordova, I am attempting to set the screen orientation to landscape for Android. Utilizing the screen-orientation plugin found at: https://www.npmjs.com/package/cordova-plugin-screen-orientation In my JavaScript code, I have impleme ...

What is the best way to handle this Json string that has been escaped using Gson in Java

So I keep receiving responses like the one below that I can't seem to handle: { "message": "someName someLastName has sent you a question", "parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastN ...

Converting a JSON array into a Java map

I am currently working on a project that involves receiving a JSON response from my API using entities and DTO. Here is an example of the response structure: return XXXResponseDTO .builder() .codeTypeList(commonCodeDetailL ...

Reset the Azure DevOps repository back to its original state if the unit tests in the pipeline are unsuccessful

Our team utilizes an Azure Pipeline that integrates with a repository to convert .json files containing customer orders into C# objects. In order to prevent issues with outdated data, we have implemented a script that 'Migrates' these old .json f ...

Dealing with query strings within routeprovider or exploring alternative solutions

Dealing with query strings such as (index.php?comment=hello) in routeprovider configuration in angularjs can be achieved by following the example below: Example: angular.module('app', ['ngRoute']) .config(function($routeProvider, $loc ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

revealing a particular field in jQuery during the validation process

Edit: Currently, I am utilizing the jquery validate plugin and have hidden all error messages initially. Upon checking a specific input field, my objective is to unhide the error message if it is invalid without causing error messages to appear in other f ...

html - automatically populating input fields when the page loads

Currently, I have an HTML form embedded in the view and I am looking for a way to automatically populate specific input fields with json variables obtained from the server. Instead of manually writing JavaScript code for each field, my goal is to access th ...

I need help converting the "this week" button to a dropdown menu. Can someone assist me in troubleshooting what I am missing?

Seeking assistance with customizing the "this week" button on the free admin dashboard template provided by Bootstrap 4. Looking to turn it into a dropdown feature but unable to achieve success after two days of research and watching tutorials. See code sn ...

Limit the ng-repeat results based on search input using a transformation filter

I am currently working with an array of records that are being displayed in an HTML table with filters in the header. However, I have encountered an issue where some values are transformed by filters, causing the ng-repeat filter to fail. <table class= ...

Assign a unique variable to each div simultaneously

I am looking to implement a countdown feature for each DIV with the class (.topitembox) by incorporating specific JSON variables. $('#countdown_items .topitembox').each(function () { itmID = $(this).attr('class').replace(/[^0-9]/g, ...

Execute and generate a continuous loop in JavaScript

I successfully implemented an image slider using pure PHP, but encountered issues when integrating it into Yii framework. The images were not loading due to the following reasons: - JavaScript block was not loading image numbers. - I am unsure how to load ...

PHP can either transform JSON values to include keys, or PostgreSQL can assign values to keys

My main goal is to store text data, where each row has its own separate date. Either... 1. How can I extract the values from the provided format and store them in a PHP array for iteration using a foreach loop? ...or... 2. What is the correct method to ...

What is the best way to showcase the information stored in Firestore documents on HTML elements?

Currently in the process of designing a website to extract data from my firestore collection and exhibit each document alongside its corresponding fields. Below is the code snippet: <html> <!DOCTYPE html> <html lang="en"> <head> ...

Send an ArrayList to jQuery Flot

Good day. Apologies for any language barriers as English is not my first language. I am a novice in [see tags] and I have a web application that gathers a date and a serial number to execute a SQL query. The query returns some data (measurement values an ...

Denied rendering of design due to incompatible MIME type

Just delved into the world of node / express and decided to test my skills by creating a simple tip calculator app. However, I seem to have hit a roadblock with loading my CSS. The console keeps throwing this error: "Refused to apply style from &apos ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...