如何使用 Sinatra 和 DataMapper 解析 json 并将数据写入数据库
我正在这里进行概念验证,但遇到的麻烦比我想象的要多一些。这是我想做的事情以及我目前正在做的事情。
我正在向我的 Sinatra 应用程序发送一个 json 文件,其中包含以下简单消息。
[
{
title: "A greeting!",
message: "Hello from the Chairman of the Board"
}
]
从那里我有一篇文章,我用它来获取参数并将它们写入 sqlite 数据库
post '/note' do
data = JSON.parse(params) #<---EDIT - added, now gives error.
@note = Note.new :title => params[:title],
:message => params[:message],
:timestamp => (params[:timestamp] || Time.now)
@note.save
end
当我发送消息时,时间戳和 id 会保存到数据库中,但标题和消息为零。
我缺少什么?
谢谢
编辑:
现在,当我运行我的应用程序并向其发送 json 文件时,我收到此错误:
C:/Users/Norm/ruby/Ruby192/lib/ruby/1.9.1/webrick/server.rb:183:in `block在start_thread'中 类型错误:无法将哈希转换为字符串
编辑2:取得了一些成功。
我将上面的 json 放在一个名为 test.json 的文件中,这是发布 json 的方式。为了发布文件,我使用了 HTTPClient:
require 'httpclient'
HTTPClient.post 'http://localhost:4567/note', [ :file => File.new('.\test.json') ]
经过更多思考,我认为发布文件是问题所在,所以我尝试以不同的方式发送它。一旦我将我的帖子/注释句柄更改为以下内容,下面的示例就起作用了:
data = JSON.parse(request.body.read)
我的新 send.rb
require 'net/http'
require 'rubygems'
require 'json'
@host = 'localhost'
@port = '4567'
@post_ws = "/note"
@payload ={
"title" => "A greeting from...",
"message" => "... Sinatra!"
}.to_json
def post
req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
#req.basic_auth @user, @pass
req.body = @payload
response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:
#{response.body}"
end
thepost = post
puts thepost
所以我越来越接近了。感谢迄今为止所有的帮助。
I'm doing a proof of concept thing here and having a bit more trouble than I thought I was going to. Here is what I want to do and how I am currently doing it.
I am sending my Sinatra app a json file which contains the simple message below.
[
{
title: "A greeting!",
message: "Hello from the Chairman of the Board"
}
]
From there I have a post which I am using to take the params and write them to sqlite database
post '/note' do
data = JSON.parse(params) #<---EDIT - added, now gives error.
@note = Note.new :title => params[:title],
:message => params[:message],
:timestamp => (params[:timestamp] || Time.now)
@note.save
end
When I send the message the timestamp and the id are saved to the database however the title and message are nil.
What am I missing?
Thanks
Edit:
Now when I run my app and send it the json file I get this error:
C:/Users/Norm/ruby/Ruby192/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
TypeError: can't convert Hash into String
Edit 2: Some success.
I have the above json in a file call test.json which is the way the json will be posted. In order to post the file I used HTTPClient:
require 'httpclient'
HTTPClient.post 'http://localhost:4567/note', [ :file => File.new('.\test.json') ]
After thinking about it some more, I thought posting the file was the problem so I tried sending it a different way. The example below worked once I changed n my post /note handle to this:
data = JSON.parse(request.body.read)
My new send.rb
require 'net/http'
require 'rubygems'
require 'json'
@host = 'localhost'
@port = '4567'
@post_ws = "/note"
@payload ={
"title" => "A greeting from...",
"message" => "... Sinatra!"
}.to_json
def post
req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
#req.basic_auth @user, @pass
req.body = @payload
response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:
#{response.body}"
end
thepost = post
puts thepost
So I am getting closer. Thanks for all the help so far.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Sinatra 不会自动为您解析 JSON,但幸运的是解析 JSON 非常简单:
像往常一样从需要它开始。
require 'rubygems'
如果您使用的不是 Ruby 1.9+:这是一个往返用途,用于创建然后解析一些 JSON。 IRB 输出显示哈希和嵌入数组已转换为 JSON,然后解析回哈希。你应该能够将其分解以满足你的邪恶需求。
为了获取这些字段,我们将进一步分解上面的示例,并假设我们已从连接的远程端收到 JSON。因此,下面的
received_json
是传入的数据流。将其传递给 JSON 解析器,您将得到 Ruby 数据哈希值。像平常一样访问哈希并获取值:传入的 JSON 可能是您的
params[]
哈希中的一个参数,但我不确定它会隐藏在哪个键下,因此您将需要弄清楚这一点。它可能被称为'json'
或'data'
但这是特定于应用程序的。您的数据库代码看起来没问题,并且如果您看到写入其中的一些数据,则一定可以正常工作。看起来您只需要从 JSON 中检索字段即可。
Sinatra won't parse the JSON automatically for you, but luckily parsing JSON is pretty straightforward:
Start with requiring it as usual.
require 'rubygems'
if you're not on Ruby 1.9+:That's a roundtrip use to create, then parse some JSON. The IRB output shows the hash and embedded array were converted to JSON, then parsed back into the hash. You should be able to break that down for your nefarious needs.
To get the fields we'll break down the example above a bit more and pretend that we've received JSON from the remote side of your connection. So, the
received_json
below is the incoming data stream. Pass it to the JSON parser and you'll get back a Ruby data hash. Access the hash as you would normally and you get the values:The incoming JSON is probably a parameter in your
params[]
hash but I am not sure what key it would be hiding under, so you'll need to figure that out. It might be called'json'
or'data'
but that's app specific.Your database code looks ok, and must be working if you're seeing some of the data written to it. It looks like you just need to retrieve the fields from the JSON.