0

I have an array:

 arr = ["dog", "cat", "eel"]

And I'd like to convert it into a JSON like so:

'{"dog": {}, "cat": {}, "eel": {} }'

And NOT:

'{"dog"=> {}, "cat"=> {}, "eel"=> {} }'

I've tried using:

res = arr.each_with_object({}) { |k,h| h[k] = {} }

I feel like I'm missing something quite obvious. Is there a way to single quote it upon response?

1 Answer 1

6

Try the below code :

require 'json'

arr = ["dog", "cat", "eel"]
puts Hash[arr.each_with_object({}).to_a].to_json
# >> {"dog":{},"cat":{},"eel":{}}
puts Hash[arr.map{|e| [e,{}]}].to_json # you can do this way also
# >> {"dog":{},"cat":{},"eel":{}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.