问题
So I have a very simple rabl view that will support output for both xml and json (curr.rabl):
collection @currencies => "currencies"
attributes :code, :name
My rabl config:
Rabl.configure do |config|
config.include_json_root = false
config.include_child_root = false
config.xml_options = { :skip_types => true, :camelize => :lower }
config.include_xml_root = false
end
Output that rabl gives for xml and json:
XML:
<currencies>
<currency>
<code>AFN</code>
<name>Afghan Afghani</name>
</currency>
<currency>
<code>AFA</code>
<name>Afghanistan Afghani</name>
</currency>
</currencies>
JSON:
{
currencies: [
{
code: "AFN",
name: "Afghan Afghani"
},
{
code: "AFA",
name: "Afghanistan Afghani"
}]}
To me, this is not correct. The JSON should look like the following according to what I've been reading:
{
currencies: {currency: [
{
code: "AFN",
name: "Afghan Afghani"
},
{
code: "AFA",
name: "Afghanistan Afghani"
} ] }
}
If I set the config.include_child_root(/include_json_root) = true
, then I get the following (still not correct)
{
currencies: [
{
currency: {
code: "AFN",
name: "Afghan Afghani"
}
},
{
currency: {
code: "AFA",
name: "Afghanistan Afghani"
} } ] }
First, am I correct in my assumption that RABL is outputting the wrong json? Second, is there a way to get RABL to do what I want for this view, as well as any other view that may have many nested child objects?
回答1:
Just to be clear this is definitely not standard:
{
currencies: {currency: [
{
code: "AFN",
name: "Afghan Afghani"
},
{
code: "AFA",
name: "Afghanistan Afghani"
} ] }
}
Both forms RABL produces are standard. One without root and one with. This thing above doesn't make any sense, I have never seen any API act that way.
回答2:
I always used the second form of what you have above:
{
currencies: [
{
currency: { ... },
},
{
currency: { ... }
}]
}
If you really want to do this:
{
currencies: { currency: [ { ... }, { ... }] }
}
I think you can set include_json_root to false and use custom nodes but it might get complicated.
来源:https://stackoverflow.com/questions/13590508/does-rabls-json-output-not-conform-to-standard-can-it