Ruby - Microsoft Translator意外令牌错误

时间:2012-01-09 10:59:09

标签: ruby json

我正在使用以下方法通过调用:

将简单的单词从英语翻译成俄语

translate("hello")

这是我的方法:

def translate(text)

    begin

        uri = "http://api.microsofttranslator.com/V2/Ajax.svc/GetTranslations?appId=#{@appid}&text=#{text.strip}&from=en&to=ru&maxTranslations=1"
        page = HTTParty.get(uri).body
        show_info = JSON.parse(page) # this line throws the error

    rescue

        puts $!

    end

end

JSON输出:

{"From":"en","Translations":[{"Count":0,"MatchDegree":100,"MatchedOriginalText":"","Rating":5,"TranslatedText":"Привет"}]}

错误:

unexpected token at '{"From":"en","Translations":[{"Count":0,"MatchDegree":100,"MatchedOriginalText":"","Rating":5,"TranslatedText":"Привет"}]}'

不确定unexpected token的含义。这是我收到的唯一错误。不幸的是,我无法修改由API本身返回的JSON输出。

更新

看起来API正在返回一些非法字符(糟糕的Microsoft):

'´╗┐{"From":"en","Translations":[{"Count":0,"MatchDegree":0,"Matched OriginalText":"","Rating":5,"TranslatedText":"Hello"}]}'

完整错误:

C:/Ruby193/lib/ruby/1.9.1/json/common.rb:148:in `parse': 743: unexpected token at '´╗┐{"From":"en","Translations":[{"Count":0,"MatchDegree":0,"Matched
OriginalText":"","Rating":5,"TranslatedText":"Hello"}]}' (JSON::ParserError)
        from C:/Ruby193/lib/ruby/1.9.1/json/common.rb:148:in `parse'
        from trans.rb:13:in `translate'
        from trans.rb:17:in `<main>'

1 个答案:

答案 0 :(得分:1)

尝试确保UTF-8编码并剥离字符串中的任何前导BOM指标:

# encoding: UTF-8
# ^-- Make sure this is on the first line!

def translate(text)
  begin
    uri = "http://api.microsofttranslator.com/V2/Ajax.svc/GetTranslations?appId=#{@appid}&text=#{text.strip}&from=en&to=ru&maxTranslations=1"
    page = HTTParty.get(uri).body
    page.force_encoding("UTF-8").gsub!("\xEF\xBB\xBF", '')
    show_info = JSON.parse(page) # this line throws the error
  rescue
      puts $!
  end
end

<强>来源: