def utf8_to_json(string)
i, n, result = 0, string.size, ''
while i < n
char = string[i]
case
when char == ?\b then result << '\b'
when char == ?\t then result << '\t'
when char == ?\n then result << '\n'
when char == ?\f then result << '\f'
when char == ?\r then result << '\r'
when char == ?" then result << '\"'
when char == ?\\ then result << '\\\\'
when char.between?(0x0, 0x1f) then result << "\\u%04x" % char
when char.between?(0x20, 0x7f) then result << char
when !(JSON.support_unicode? && $KCODE == 'UTF8')
result << char
when char & 0xe0 == 0xc0
result << '\u' << utf8_to_utf16(string[i, 2])
i += 1
when char & 0xf0 == 0xe0
result << '\u' << utf8_to_utf16(string[i, 3])
i += 2
when char & 0xf8 == 0xf0
result << '\u' << utf8_to_utf16(string[i, 4])
i += 3
when char & 0xfc == 0xf8
result << '\u' << utf8_to_utf16(string[i, 5])
i += 4
when char & 0xfe == 0xfc
result << '\u' << utf8_to_utf16(string[i, 6])
i += 5
else
raise JSON::UnparserError, "Encountered unknown UTF-8 byte: %x!" % char
end
i += 1
end
result
end