Skip to content

Instantly share code, notes, and snippets.

@r7kamura
Last active November 24, 2020 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r7kamura/2e4c8e4508c6a1fa2cadbe5052f8398f to your computer and use it in GitHub Desktop.
Save r7kamura/2e4c8e4508c6a1fa2cadbe5052f8398f to your computer and use it in GitHub Desktop.
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