Does RABL's JSON output not conform to standard? Can it?

走远了吗. 提交于 2019-12-13 04:47:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!