【发布时间】:2017-05-18 18:06:24
【问题描述】:
我是 Rails 新手,对如何从 API 调用中获取 JSON 字符串并将其存储到我的模型中有点迷茫。我绕着圈子试图弄清楚。
例如,我从我的 API 调用中收到以下信息。
{"FileType"=>nil, "Text"=>nil, "TextCode"=>nil, "Html"=>nil, "HtmlCode"=>nil, "Rtf"=>nil, "RtfCode"=>nil, "CreditsRemaining"=>0, "FileExtension"=>nil, "Pdf"=>nil, "PdfCode"=>nil, "CandidateImage"=>nil, "CandidateImageExtension"=>nil, “代码”=>“错误”、“子代码”=>“身份验证错误”、“消息”=>“无效 AccountId:您提供的‘AccountId’无效。", "ParsedDocument"=>无}
我想将此插入到我的 Resume 模型中,因此我创建了以下 Helper。
require 'rest-client'
require 'base64'
require 'json'
module ResumesHelper
def parser
FILE_NAME = "test.docx"
# Perform a binary read of the entire file
fileBuf = File.open(FILE_NAME,"rb") {|io| io.read}
base64 = Base64.encode64(fileBuf)
params = "{\"FileBytes\":" + "\"" + base64 + "\"," +
"\"AccountId\": \"MyID\",
\"ServiceKey\": \"MyKey\"}"
response = RestClient::Request.execute(
method: :post,
url: 'http://example/api',
payload: params,
headers: {"Content-Type" => "application/json"}
)
a_hash = JSON.parse(response)
new_record = Resume.new
new_record.attribute_1 = a_hash['Message']
new_record.save
end
我收到一个错误,指出脚本的语法不正确。请让我知道我在这里做错了什么或指出正确的方向。
【问题讨论】:
-
(1) 您应该发布错误消息,因为这通常会有所帮助,并且 (2) 那是您的实际代码吗?如果是这样,至少,看起来你没有用
end关闭def。 -
\"ServiceKey\"这部分可能是错的
标签: ruby-on-rails json database