unicode字符串的字节表示

时间:2018-02-13 10:43:45

标签: python python-3.x unicode utf-8 lua

这是python3代码:

>>> bytes(json.dumps({'Ä':0}), "utf-8")
b'{"\\u00c4": 0}'

json.dumps()返回unicode字符串,bytes()返回其' bytes表示 - 字符串编码为utf-8

如何在Lua中获得相同的结果?我需要一个包含非ascii字符的json对象的字节表示。

2 个答案:

答案 0 :(得分:2)

你必须手动完成。

local json = require('json')
local x = {['Ä'] = 0}
local y = json.encode(x)
print(y)                       -->  {"Ä":0}
local z = utf8_to_python(y)
print(z)                       -->  {"\\u00c4":0}

用法:

value !== undefined

答案 1 :(得分:0)

使用string.gsub的简单版本:

local function python_escape(str)
  return (string.gsub(
    str,
    -- leading byte followed by one or more continuation bytes;
    -- decimal version for Lua 5.1: "[\194-\244][\128-\191]+",
    "[\xC2-\xF4][\x80-\xBF]+"
    function (non_ASCII)
      local codepoint = utf8.codepoint(non_ASCII)
      if codepoint <= 0xFFFF then
        return ("\\u%04x"):format(codepoint)
      else
        return ("\\U%08x"):format(codepoint)
      end
    end))
end

我在返回值(string.gsub(--[[...]]))周围添加了括号,以去掉string.gsub的第二个返回值(替换次数)。