Last active
November 24, 2020 00:50
-
-
Save r7kamura/2e4c8e4508c6a1fa2cadbe5052f8398f to your computer and use it in GitHub Desktop.
Ruby script to GET JSON then convert it to XML.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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