gpt4 book ai didi

错误为 "illegal/malformed utf-8"的 Ruby to_json 问题

转载 作者:数据小太阳 更新时间:2023-10-29 06:38:41 27 4
gpt4 key购买 nike

我在尝试将散列转换为 json 字符串时遇到错误 JSON::GeneratorError: source sequence is illegal/malformed utf-8。我想知道这是否与编码有关,我怎样才能让 to_json 只按原样对待\xAE?

$ irb
2.0.0-p247 :001 > require 'json'
=> true
2.0.0-p247 :002 > a = {"description"=> "iPhone\xAE"}
=> {"description"=>"iPhone\xAE"}
2.0.0-p247 :003 > a.to_json
JSON::GeneratorError: source sequence is illegal/malformed utf-8
from (irb):3:in `to_json'
from (irb):3
from /Users/cchen21/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'

最佳答案

\xAE 不是 UTF-8 中的有效字符,您必须改用 \u00AE:

"iPhone\u00AE"
#=> "iPhone®"

或者进行相应的转换:

"iPhone\xAE".force_encoding("ISO-8859-1").encode("UTF-8")
#=> "iPhone®"

关于错误为 "illegal/malformed utf-8"的 Ruby to_json 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18067203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com