How to parse json and write this data to a database using Sinatra and DataMapper

I am doing a proof of concept here and have a bit more problems than I thought I was going to. This is what I want to do and how I do it now.

I am sending my Sinatra application to a json file containing a simple message below.

[ 
        { 
        title: "A greeting!",
        message: "Hello from the Chairman of the Board" 
         }
]

From there, I have a message that I use to take parameters 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 a message, the timestamp and identifier are stored in the database, but the header and message are null.

What am I missing?

thank

Edit:

Now, when I run my application and send it to a json file, I get this error:

C: /Users/Norm/ruby/Ruby192/lib/ruby/1.9.1/webrick/server.rb: 183: in a block in start_thread 'TypeError: cannot convert Hash to string

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

, . .

+3
1

Sinatra JSON , , , JSON :

, . require 'rubygems' Ruby 1.9 +:

>> require 'json' #=> true
>> a_hash = {'a' => 1, 'b' => [0, 1]} #=> {"a"=>1, "b"=>[0, 1]}
>> a_hash.to_json #=> "{"a":1,"b":[0,1]}"
>> JSON.parse(a_hash.to_json) #=> {"a"=>1, "b"=>[0, 1]}

, , JSON. IRB , JSON, . .

, , JSON . , received_json - . JSON, - Ruby. , , :

>> received_json = a_hash.to_json #=> "{"a":1,"b":[0,1]}"
>> received_hash = JSON.parse(received_json) #=> {"a"=>1, "b"=>[0, 1]}
>> received_hash['a'] #=> 1
>> received_hash['b'] #=> [0, 1]

JSON, , params[], , , . 'json' 'data', .

, , . , JSON.

+6

Source: https://habr.com/ru/post/1775855/


All Articles