Ask A Question

Notifications

Youโ€™re not receiving notifications from this thread.

Parsing a Ruby hash sent to a Javascript API

Daniel Weaver asked in Javascript โ€ข

Sending data from Rails via HTTParty to a Node endpoint:

params = { str: "word", bool: true, hash: { number: 123 } }
result = HTTParty.get("http://localhost/test.js", query: params)

It works fine without the nested hash in the params but when I add that in things get hairy.

If I send it as shown above the Node endpoint receives:
GET /test.js?str=word&bool=true&hash[number]=123 and hash is undefined

If I convert the nested hash to a string:
params = { str: "word", bool: true, hash: { number: 123 }.to_s } then Node receives this:
GET /test.js?str=word&bool=true&hash=%7B%3Anumber%3D%3E123%7D and hash is available in JS as: "{:number=>123}" but I can't figure out how to convert this to a JS object.

If I convert the nested hash to query:
params = { str: "word", bool: true, hash: { number: 123 }.to_query } then Node receives this:
GET /test.js?str=word&bool=true&hash=number%3D123 and hash is available in JS as: "number=123".

How do I access that nested hash in JS? How do I convert it to a usable object? I don't mind which of the various ways to send the nested params, I just to access them easily.

Reply

The answer turned out to be very simple, of course ๐Ÿ˜‰

Use to_json on the nested params in Ruby:
params = { str: "word", bool: true, hash: { number: 123 }.to_json }
which sends:
GET /test.js?str=word&bool=true&hash=%7B%22number%22%3A123%7D
resulting in hash as {"number":123} in JS.

Use regular JSON parse to get the value: JSON.parse(hash).number gives 123 ๐ŸŽ‰

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 79,047+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.