当'¿'存在时,无法将数组数据转换为json

unk*_*its 0 ruby json

这是我的红宝石代码

require 'json'
a=Array.new
value="¿value"
data=value.gsub('¿','-')
a[0]=data
puts a
puts "json is"
puts jsondata=a.to_json
Run Code Online (Sandbox Code Playgroud)

得到以下错误

C:\Ruby193>new.rb
C:/Ruby193/New.rb:3: invalid multibyte char (US-ASCII)
C:/Ruby193/New.rb:3: syntax error, unexpected tIDENTIFIER, expecting $end
value="?value"
            ^
Run Code Online (Sandbox Code Playgroud)

ick*_*fay 5

这不是JSON问题 - Ruby无法解码您的源,因为它包含多字节字符.默认情况下,Ruby尝试将文件解码为US-ASCII,但¿在US-ASCII中无法表示,因此失败.解决方案是提供文档中描述的魔术评论.假设您的源文件的编码是UTF-8,您可以这样告诉Ruby:

# encoding: UTF-8
# ...
value = "¿value"
# ...
Run Code Online (Sandbox Code Playgroud)