0

I have a hash

{:name =>"douglas_hettinger@braunlebsack.io"}

I am trying to convert this hash into the following JavaScript format.

{"name" : "douglas_hettinger@braunlebsack.io"}

I tried:

{:name=>"douglas_hettinger@braunlebsack.io"}.to_json

which gives the output:

"{\"name\":\"douglas_hettinger@braunlebsack.io\"}"

Parsing it with JSON gives:

JSON.parse({:name=>"douglas_hettinger@braunlebsack.io"}.to_json) 
# => {"name"=>"douglas_hettinger@braunlebsack.io"}
sawa
  • 165,429
  • 45
  • 277
  • 381
Bloomberg
  • 2,317
  • 2
  • 25
  • 47
  • I think the top answer here is what you are looking for http://stackoverflow.com/questions/3183786/how-to-convert-a-ruby-hash-object-to-json – Danoram Feb 16 '17 at 04:06
  • 2
    `"{\"name\":\"douglas_hettinger@braunlebsack.io\"}"` is the `inspect` of the string, the default way strings are presented in console. The string *content* (escaped by backslashes by `inspect`, which is why you may have thought the result to be wrong) is: `{"name":"douglas_hettinger@braunlebsack.io"}`, exactly what you want. use `puts {...}.to_json` instead of just `{...}.to_json` in console to verify this. – Amadan Feb 16 '17 at 04:14
  • What is your question? – sawa Feb 16 '17 at 05:09

2 Answers2

1

to_json should work:

require 'json'
{:name =>"douglas_hettinger@braunlebsack.io"}.to_json
#=> "{"name":"douglas_hettinger@braunlebsack.io"}"
Shannon
  • 2,988
  • 10
  • 21
0

What I understand is that you want to recreate the same hash that you converted to JSON.

This could be done by passing option symbolize_names: true to JSON.parse method.

The code would look something like this

JSON.parse({:name=>"douglas_hettinger@braunlebsack.io"}.to_json, symbolize_names: true)