harinsamaranayake
harinsamaranayake

Reputation: 961

What is the difference between to_json VS JSON.parse() in Ruby?

Can someone explain the difference between to_json and JSON.parse() in Ruby?

Upvotes: 0

Views: 1028

Answers (1)

radoAngelov
radoAngelov

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

Related Questions