JSON dump in Ruby

 

In Ruby, the json library’s API differs from Python’s json.dump.

The equivalent in Ruby would be something like this:

require 'json'

data = {
  name: "Christopher",
  message: "こんにちは世界"  # Japanese characters to test non-ASCII
}

# Pretty-print with indentation and allow non-ASCII characters
json_str = JSON.pretty_generate(data, indent: '  ', ascii_only: false)

puts json_str

 

Explanation:

  • JSON.pretty_generate(obj, opts = {}) → gives indentation and line breaks.

  • indent: ' ' → sets 2-space indentation.

  • ascii_only: false → prevents escaping non-ASCII characters (i.e., keeps UTF-8 characters intact).

  • Ruby doesn’t have ensure_ascii like Python, but ascii_only: false is the direct counterpart.

If instead you want to dump directly to a file (like Python’s json.dump does):

File.open("output.json", "w:utf-8") do |f|
  f.write(JSON.pretty_generate(data, indent: '  ', ascii_only: false))
end

 


Would you like me to also show you the non-pretty (compact but still UTF-8 safe) equivalent of Python’s json.dump(..., ensure_ascii=False) without indentation?

 

posted @ 2025-09-27 20:30  profesor  阅读(5)  评论(0)    收藏  举报