to_json VS JSON.parse()

Iman Tung
May 16, 2021

--

One thing about ruby that I love (or hate) that we can literally read it aloud on conversation language and programmatically still working.

3.times do
# something
end

However, this is not always the case in handling JSON, we should note that "quoted text" is actually a valid JSON format, therefore we can't casually write s.to_json to convert text to JSON object but instead use JSON.parse()

s = '{"hello": "world"}'

# Wrong
# Output => "\"{\\\"hello\\\": \\\"world\\\"}\""
s.to_json

# Right
# Output => {"hello"=>"world"}
JSON.parse(s)

m = {hello: 'world'}

# Right
# Output => "{\"hello\":\"world\"}"
m.to_json

Conclusion: Use to_json when the variable is the map. Use JSON.parse() if the variable is a string. The same thing with to_s and JSON.generate()

Previously published in https://imantung.github.io at 23 Aug 2017

--

--

Iman Tung
Iman Tung

Written by Iman Tung

Technology to write, life to grateful. Overthinking is good, only if it has the output. Fundamental is the main concern.

No responses yet