Beginning rails programmer here. I’m trying to convert a hash to both xml and json, but the output is different.
Here’s the hash:
{:exchangeRates=>[{:baseCurrency=>"USD", :quoteCurrency=>"EUR", :amount=>1, :nprices=>1, :conversions=>[{:date=>Tue, 20 Nov 2012 21:00:00 +0000, :ask=>"0.7813", :bid=>"0.7813"}]}, {:baseCurrency=>"CAD", :quoteCurrency=>"EUR", :amount=>1, :nprices=>1, :conversions=>[{:date=>Tue, 20 Nov 2012 21:00:00 +0000, :ask=>"0.7839", :bid=>"0.7837"}]}]}
Here’s the corresponding render code
format.json { render :json => { :response => rates.to_hash() } }
and here’s the JSON (which is what I want)
{"response": {"exchangeRates": [
{
"baseCurrency": "USD",
"quoteCurrency": "EUR",
"amount": 1,
"nprices": 1,
"conversions": [{
"date": "2012-11-20T21:00:00+00:00",
"ask": "0.7813",
"bid": "0.7813"
}]
},
{
"baseCurrency": "CAD",
"quoteCurrency": "EUR",
"amount": 1,
"nprices": 1,
"conversions": [{
"date": "2012-11-20T21:00:00+00:00",
"ask": "0.7839",
"bid": "0.7837"
}]
}
]}}
Here’s my xml render code:
format.xml { render :xml => rates.to_hash(), :root => 'response' }
Here’s the xml output (there are extra tags where I put in arrays):
<response>
<exchangeRates type="array">
<exchangeRate>
<baseCurrency>USD</baseCurrency>
<quoteCurrency>EUR</quoteCurrency>
<amount type="integer">1</amount>
<nprices type="integer">1</nprices>
<conversions type="array">
<conversion>
<date type="datetime">2012-11-20T21:00:00+00:00</date>
<ask>0.7813</ask>
<bid>0.7813</bid>
</conversion>
</conversions>
</exchangeRate>
<exchangeRate>
<baseCurrency>CAD</baseCurrency>
<quoteCurrency>EUR</quoteCurrency>
<amount type="integer">1</amount>
<nprices type="integer">1</nprices>
<conversions type="array">
<conversion>
<date type="datetime">2012-11-20T21:00:00+00:00</date>
<ask>0.7839</ask>
<bid>0.7837</bid>
</conversion>
</conversions>
</exchangeRate>
</exchangeRates>
</response>
As you can see, it is adding the extra “array” attribute tags, i.e. exchangeRates and conversions. How do I get this to format the same as the json? I also don’t want the attributes on any of the tags either. I know you can pass in attributes, such as :root => ‘response’, but after looking for quite some time, I can’t seem to find a listing of these attributes on the web.
Any help would be greatly appreciated, thanks!
This is a case where it’s best just to go directly to the source code. The
to_xmlmethod is in theActiveModel::Serializermodule, here are the inline docs, which don’t mention anything about thetype="array"attribute tags. Dig a bit deeper though and you’ll see they appear in the same file on line 130 of a method calledadd_associations.rails/activemodel/lib/active_model/serializers/xml.rb:130
That tells us that there’s an option called
skip_types, which appears to be documented nowhere. Try passing that toto_xml, and you get the desired behaviour:You’ll notice all the added
typeattributes are gone.So just pass the same option to
renderand you’ll get the desired result: