How to Convert CSV to JSON with Ruby Script

How to convert CSV to JSON with ruby script

How to Convert CSV to JSON with Ruby Script

The Ruby script builds JSON using the first line of the CSV file to determine the appropriate elements and the corresponding data, as well as checking that integers and strings are converted to their appropriate (typed) formats. And the script seems fairly robust; I noticed hardly a pause when throwing a 14,000-line CSV file at it. There are no built-in specifics to the data mapping; you’ll need to handle that either by modifying the script or handling

Ruby Script to Convert CSV to JSON:

From the below post I will explain How to convert CSV to JSON with Ruby Script:

#!/usr/bin/env ruby

require 'nexpose'

require 'csv'

require 'json'

require 'open-uri'

require 'fileutils'

require 'zlib'

include Nexpose

#Logging into Nexpose.

#Provide the IP/Hostaname, Username and Password of the Nexpose Console

puts('Logging into Nexpose')

nsc = Nexpose::Connection.new('localhost', 'username', 'password');

begin

nsc.login

rescue ::Nexpose::APIError => err

$stderr.puts("Connection failed: #{e.reason}")

exit(1)

end

puts 'logged into Nexpose'

#Listing all the sites created in Nexpose

sites = nsc.list_sites

puts(sites)

#Report generation for user specified site. Select the site ID for which CSV Report has to be generated.


#Select a specific site and Site_ID can be seen on the URL

report = ReportConfig.new('CSV Export5', 'basic-vulnerability-check-results', 'csv')

report.add_filter('site', 156)

id = report.save(nsc, true)

puts "Report saved with ID #{id}"

until nsc.last_report(id)

puts 'waiting . . .'

end

puts(nsc)

last = nsc.last_report(id)

puts(last.uri)

newurl="/opt/rapid7/nexpose/nsc/htroot"+last.uri+".gz"

newurl1="/opt/rapid7/nexpose/nsc/htroot"+last.uri

puts(newurl)

 

#Sleep is introduced to wait for report generation. It can be increased if report size is large.

sleep(5)

#Reading the CSV file and converting the same to JSON

Zlib::GzipReader.open(newurl) do | input_stream |

File.open(newurl1, "w") do |output_stream|

IO.copy_stream(input_stream, output_stream)

 end

end

extracted_data   = CSV.table(newurl1)

transformed_data = extracted_data.map { |row| row.to_hash }

File.open('report.json', 'w') do |file|

file.puts JSON.pretty_generate(transformed_data)

end

exit

If you were not able to execute the above process of Ruby Scrip to Convert CSV to JSON then you can Contact us.