Skip to content

Instantly share code, notes, and snippets.

@repeatedly
Created December 16, 2015 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save repeatedly/a68698b7aa28195b0403 to your computer and use it in GitHub Desktop.
Save repeatedly/a68698b7aa28195b0403 to your computer and use it in GitHub Desktop.
JSON encode / decode comparison
# Result
#valid
#{"k"=>"vvv"}
#{"k"=>"vvv"}
#{"k"=>"vvv"}
#invalid utf-8 with US-ASCII
#{"k"=>"v\xFFvv"}
#{"k"=>"v\xFFvv"}
#"Yajl: error: lexical error: invalid bytes in UTF8 string.\n # {\"k\":\"v\xFFvv\"}\n (right here) ------^\n"
require 'json'
require 'oj'
require 'yajl'
json = "{\"k\":\"vvv\"}"
puts "valid"
begin
p JSON.parse(json)
rescue => e
p "JSON: error: #{e}"
end
begin
p Oj.load(json)
rescue => e
p "Oj: error: #{e}"
end
begin
p Yajl.load(json)
rescue => e
p "Yajl: error: #{e}"
end
json = "{\"k\":\"v#{0xff.chr}vv\"}"
puts "invalid utf-8 with US-ASCII"
begin
p JSON.parse(json)
rescue => e
p "JSON: error: #{e}"
end
begin
p Oj.load(json)
rescue => e
p "Oj: error: #{e}"
end
begin
p Yajl.load(json)
rescue => e
p "Yajl: error: #{e}"
end
# Result
#valid
#"{\"k\":\"vvv\"}"
#"{\"k\":\"vvv\"}"
#"{\"k\":\"vvv\"}"
#invalid utf-8 with US-ASCII
#"JSON: error: \"\\xFF\" from ASCII-8BIT to UTF-8"
#"{\"k\":\"v\xFFvv\"}"
#"{\"k\":\"v\xFFvv\"}"
require 'json'
require 'oj'
require 'yajl'
json = {"k" => "vvv"}
puts "valid"
begin
p JSON.dump(json)
rescue => e
p "JSON: error: #{e}"
end
begin
p Oj.dump(json)
rescue => e
p "Oj: error: #{e}"
end
begin
p Yajl.dump(json)
rescue => e
p "Yajl: error: #{e}"
end
json = {"k" => "v#{0xff.chr}vv"}
puts "invalid utf-8 with US-ASCII"
begin
p JSON.dump(json)
rescue => e
p "JSON: error: #{e}"
end
begin
p Oj.dump(json)
rescue => e
p "Oj: error: #{e}"
end
begin
p Yajl.dump(json)
rescue => e
p "Yajl: error: #{e}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment