0

I have a hash

{:name =>"[email protected]"}

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

{"name" : "[email protected]"}

I tried:

{:name=>"[email protected]"}.to_json

which gives the output:

"{\"name\":\"[email protected]\"}"

Parsing it with JSON gives:

JSON.parse({:name=>"[email protected]"}.to_json) 
# => {"name"=>"[email protected]"}
3
  • I think the top answer here is what you are looking for stackoverflow.com/questions/3183786/… Commented Feb 16, 2017 at 4:06
  • 2
    "{\"name\":\"[email protected]\"}" 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":"[email protected]"}, exactly what you want. use puts {...}.to_json instead of just {...}.to_json in console to verify this. Commented Feb 16, 2017 at 4:14
  • What is your question? Commented Feb 16, 2017 at 5:09

2 Answers 2

1

to_json should work:

require 'json'
{:name =>"[email protected]"}.to_json
#=> "{"name":"[email protected]"}"
Sign up to request clarification or add additional context in comments.

Comments

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=>"[email protected]"}.to_json, symbolize_names: true)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.