2

How do I capture a Json data from POST route and save it to file? I have simple ruby sinatra code as below.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'json'

post '/' do
  values = JSON.parse(request.env["rack.input"].read)
# How do I save "values" of JSON to file..
end
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
Tedha
  • 507
  • 2
  • 6
  • 14

2 Answers2

2

Try this

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'json'

post '/' do
  values = JSON.parse(request.env["rack.input"].read)
  File.open('file.txt', 'w') { |file| file.write(values) }
end
Shahzad Tariq
  • 2,767
  • 1
  • 22
  • 31
  • Thanks for posting.. but somehow it is not working for me. I don't even see the file "file.txt" in the current directory, and even if I create a file.txt, after posting, the file.txt is empty. I wonder if there something I missed. – Tedha May 06 '15 at 11:56
1

To write file in ruby you can use:

File.open('/your/path/file', 'w') { |file| file.write(values) }
Zoe
  • 27,060
  • 21
  • 118
  • 148