21

I have read data online, but it is in a string format. How can I make it so that it returns a JSON object.

Example data read:

text = '{"one":1,"two":2}'

Example conversion:

data = JSON.parse(text).to_json 

But when I do:

puts data.class
#=> String
1
  • Hi Tushortz! Make sure to mark the correct answer! Commented Aug 4, 2015 at 15:09

1 Answer 1

38

Omit to_json: it will convert the hash back to json! (JSON -> Hash -> JSON)

require 'json'
text = '{"one":1,"two":2}'
data = JSON.parse(text)  # <--- no `to_json`
# => {"one"=>1, "two"=>2}
data.class
# => Hash
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.