Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I parse json and write that data to a database using Sinatra and DataMapper
    primarykey
    data
    text
    <p>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.</p> <p>I am sending my Sinatra app a json file which contains the simple message below.</p> <pre><code>[ { title: "A greeting!", message: "Hello from the Chairman of the Board" } ] </code></pre> <p>From there I have a post which I am using to take the params and write them to sqlite database</p> <pre><code>post '/note' do data = JSON.parse(params) #&lt;---EDIT - added, now gives error. @note = Note.new :title =&gt; params[:title], :message =&gt; params[:message], :timestamp =&gt; (params[:timestamp] || Time.now) @note.save end </code></pre> <p>When I send the message the timestamp and the id are saved to the database however the title and message are nil.</p> <p>What am I missing? </p> <p>Thanks</p> <p>Edit: </p> <p>Now when I run my app and send it the json file I get this error:</p> <p>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</p> <p>Edit 2: Some success.</p> <p>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:</p> <pre><code>require 'httpclient' HTTPClient.post 'http://localhost:4567/note', [ :file =&gt; File.new('.\test.json') ] </code></pre> <p>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:</p> <pre><code>data = JSON.parse(request.body.read) </code></pre> <p>My new send.rb</p> <pre><code>require 'net/http' require 'rubygems' require 'json' @host = 'localhost' @port = '4567' @post_ws = "/note" @payload ={ "title" =&gt; "A greeting from...", "message" =&gt; "... Sinatra!" }.to_json def post req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =&gt;'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 </code></pre> <p>So I am getting closer. Thanks for all the help so far.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload