All threads / Parsing a Ruby hash sent to a Javascript API

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.

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 🎉

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.