JSON serialization: ensure_ascii

Is there a way to achieve what ensure_ascii does in python’s JSON serialization? In that I want non-7-bit-ASCII characters to come out as \u00B7?

Assuming you are dealing with deserialization, then all you need is act on String object. But if you want to encode Crystal Strings to ascii chars, then you will need to override to_json method and ensure you invoke String#dump_xxxx methods. Refer to String documentation for more details on dump and its related methods

json = %({"text": "abc 汉语"})

record Foo, text : String do
  include JSON::Serializable

  def ascii_text

str = Foo.from_json(json)
pp str.text  # =>  abc 汉语
pp str.ascii_text  # => abc \\u6C49\\u8BED


I’m dealing with serialization; thanks for the dump_unqouted tip! I can do

.to_json.gsub(/[^ -~\r\n]/){|c| c.dump_unquoted}

to get the desired result.