Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to JSON in Ruby

Tags:

json

ruby

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
like image 515
tushortz Avatar asked Aug 04 '15 12:08

tushortz


1 Answers

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
like image 88
falsetru Avatar answered Oct 17 '22 19:10

falsetru