Reputation: 961
Can someone explain the difference between to_json
and JSON.parse()
in Ruby?
Upvotes: 0
Views: 1028
Reputation: 714
They're opposite methods. to_json
converts the given object to a JSON string, while JSON.parse()
parses the given JSON string and converts it to an object:
json_string = {first_name: 'John', last_name: 'Doe'}.to_json
# => "{\"first_name\":\"John\",\"last_name\":\"Doe\"}"
json_object = JSON.parse(json_string)
# => {"first_name"=>"John", "last_name"=>"Doe"}
json_object['first_name']
# => "John"
Upvotes: 8