How to Convert JSON to Xml in Ruby

How can I convert JSON to XML in Ruby?

require 'active_support' #for to_xml() 'gem install activesupport' use the 2.3 branch
require 'json' #part of ruby 1.9 but otherwise 'gem install json'

my_json = "{\"test\":\"b\"}"
my_xml = JSON.parse(my_json).to_xml(:root => :my_root)

Also note the root argument of to_xml. If you don't specify a root it'll use the word 'hash' as the root which isn't very nice to look at.

Ruby XML to JSON Converter?

A simple trick:

First you need to gem install json, then when using Rails you can do:

require 'json'
require 'active_support/core_ext'
Hash.from_xml('<variable type="product_code">5</variable>').to_json #=> "{\"variable\":\"5\"}"

If you are not using Rails, then you can gem install activesupport, require it and things should work smoothly.

Example:

require 'json'
require 'net/http'
require 'active_support/core_ext/hash'
s = Net::HTTP.get_response(URI.parse('https://stackoverflow.com/feeds/tag/ruby/')).body
puts Hash.from_xml(s).to_json

How to convert JSON to XML? (preferably with Yahoo Pipes or Ruby)

It's quite easy to do with Yahoo! Pipes or with YQL. This is what I ended up with when using this query:

select * from json
where url='http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?term=jack+johnson&country=US&media=music&entity=musicArtist&limit=6&genreId=&version=2&output=json&callback='

URL:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D'http%3A%2%2Fitunes.apple.com%2FWebObjects%2FMZStoreServices.woa%2Fws%2FwsSearch%3Fterm%3Djack%2Bjohnson%26country%3DUS%26media%3Dmusic%26entity%3DmusicArtist%26limit%3D6%26genreId%3D%26version%3D2%26output%3Djson%26callback%3D'

How to convert a string `to_json` and `to_xml` using Ruby on Rails?

Sometimes you must add a require 'json' in your file (after installing the gem, JSON implementation for Ruby ) and do:

JSON.parse("Bad request").to_json   

or you could try:

ActiveSupport::JSON.encode("Bad request").to_json

But in your case maybe the best approach is respond correctly:

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @somearray }
format.json { render :json => @somearray }
end

Alternatively you could do:

  mystring_json = '{"bar":"foo"}'
[404, {'Content-Type' => 'application/json'}, [mysrting_json]] #json stuff
mystring_xml = '<?xml><bar>foo</bar>'
[404, {'Content-Type' => 'application/xml'}, [mysrting_xml]] #xml stuff

How to convert xml response into json and get the value from that json in Ruby on Rails?

You should deal with the hash in the first place:

response = Hash.from_xml(response)

NB: in your code Hash.from_xml(response).to_json had produced the string, containing the respective json. Now you can:

render json: response['result']

One does not need to explicitly call to_json in render, the engine will convert it on it’s own.

Sidenote: responce['result'] printing "result" string is a funny side-effect of a call to String#[] method. After to_json, response contains the string with a hash converted to json, and since there is an occurrence of "result" substring in it, the substring is printed out.

XML to JSON using Ruby and save it for separate file

I'm assuming you want to print the listing blocks to individual files as JSON. If you have access to 'active_support/core_ext' and 'nokogiri', and you aren't too concerned about how your XML is converted to JSON, you can just do:

require 'active_support/core_ext'
require 'nokogiri'

xml = Nokogiri::XML(File.read "yourfile")

xml.search("//listing").each do |l|
filename = l.at_xpath("id").content
File.open(filename + '.json', 'w') do |file|
file.print Hash.from_xml(l.to_xml).to_json
end
end

Ruby : Convert XML to JSON putting the values of Name as keys and the values of Contents as values

You can use XSLT to transform the XML and then use nokogiri to transform it:

The XSLT I used:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="resources">
{
"resources": {
<xsl:for-each select="string">
"<xsl:value-of select="./@name"/>":
"<xsl:value-of select="."/>"
<xsl:choose>
<xsl:when test="position() != last()">,</xsl:when>
</xsl:choose>
</xsl:for-each>
}
}
</xsl:template>
</xsl:stylesheet>

Apply the XSLT with nokogiri:

require 'nokogiri'
document = Nokogiri::XML(File.read('input.xml'))
template = Nokogiri::XSLT(File.read('template.xslt'))
transformed_document = template.transform(document)

Why does converting Nokogiri XML to JSON with Hash#from_xml remove content?

Hash#from_xml is an addition to the standard library Hash class made by Rails. This method is documented as troublesome in losing attributes under various conditions during the conversion from XML to Hash.

"convert XML to ruby hash with attributes" provides some suggestions.

Sources:

  • https://github.com/rails/rails/issues/588
  • https://rails.lighthouseapp.com/projects/8994/tickets/1598-preserve-xml-attributes-with-hashfrom_xml-and-activeresource
  • http://apidock.com/rails/Hash/from_xml/class

add XML support to JSON handling functions in ROR

So, you should take advantage of the standard routes and actions. In routes.rb, you might do something like:

Rails.application.routes.draw do
resources :messages
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :messages
end
end
end

Note that your controller is now nested inside api/v1. That allows you to identify the path as an api and to maintain versions over time. That solid's practice. Also note that you have a standard messages resource for your web app.

Then, your controller would look like:

class Api::V1::MessagesController < Api::V1::BaseController

def create
@message = Message.new(message_params)
respond_to do |format|
if @message.save
@message.update(url: "http://link.com/#{@message.id}")
format.json { render json: create_hsh, status: :ok }
format.xml { render xml: create_hsh, staus: :ok }
else
format.json { render json: @message.errors, status: :unprocessable_entity }
format.xml { render xml: @message.errors, status: :unprocessable_entity }
end
end
end

def show
respond_to do |format|
if @message = Message.find_by(id: params[:id])
format.json { render json: show_hsh, status: :ok }
format.xml { render xml: show_hsh, status: :ok }
else
format.json { render json: {errors: :not_found}, status: :not_found }
format.xml { render xml: {errors: :not_found}, status: :not_found }
end
end
end

private

def create_hsh
@message.attributes.with_indifferent_access.slice(:url)
end

def show_hsh
attr = @message.attributes.with_indifferent_access
attr.slice(:foo, :bar).merge!(message: attr[:text])
end

def message_params
params.require(:message).permit(:text)
end

end

Note that this controller inherits from Api::V1::BaseController. That would be a controller that you set up to do api-relevant client authentication (key/token checking, etc.). Something, perhaps, like:

class Api::V1::BaseController < ActionController::API
before_action :authorize

def authorize
# do your checks in a way that results in a variable @authorized?
render(json: {errors: :unauthorized}, status: :unauthorized) unless @authorized?
end

end

So, now you're using a single controller action to respond to all format types (that you elect to offer). Then, you clients would post something like:

http://your.api.com/messages.json

To get a json response. Or:

http://your.api.com/messages.xml 

To get an xml response. You might notice the bit that says: namespace :api, defaults: {format: 'json'} do. This means that your client could call:

http://your.api.com/messages

and it will default to the json format.

Now you don't have a bunch of random endpoints (like mssg_as_json), just the regular RESTful ones that your clients will expect. Your API clients will love you for that.

You'll note that show_hsh is the accepted code from your earlier question.



Related Topics



Leave a reply



Submit