Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to GET JSON then convert it to XML.
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'activesupport'
gem 'builder'
gem 'faraday'
gem 'faraday_middleware'
end
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/hash/conversions'
require 'faraday'
require 'faraday_middleware/response_middleware'
require 'json'
class JsonToXmlFaradayResponseMiddleware < FaradayMiddleware::ResponseMiddleware
define_parser do |body, options|
options ||= {}
options = { dasherize: false }.merge(options)
object = ::JSON.parse(body)
object.to_xml(options)
end
# @note Overriding.
def parse_response?(env)
env.response.headers['Content-Type']&.include?('application/json')
end
end
connection = Faraday.new do |connection|
connection.use(JsonToXmlFaradayResponseMiddleware)
end
url = STDIN.read.chomp
puts connection.get(url).body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment