Skip to main content

Parsing a Ruby hash sent to a Javascript API

Javascript • Asked by Daniel Weaver

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 🎉


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.