How can I convert JSON to XML in Ruby?

前端 未结 4 1548
有刺的猬
有刺的猬 2021-02-20 18:28

Is there any way to convert JSON to XML in Ruby?

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 19:22

    Regarding @rwilliams aka r-dub answer:

    ActiveSupport moved its components into separate modules for granularity. Rather than load everything all at once, we can tell it to load only certain subsets, or, if we still choose, we can load everything at once. No matter what, we can not use require 'activesupport' like we used to, instead we have to use require 'activesupport/all' or one of the subsets.

    >> require 'active_support/core_ext/array/conversions' #=> true
    >> [{:a => 1, :b => 2}, {:c => 3}].to_xml
    => "\n\n  \n  \n\n"
    

    In addition, ActiveSupport contains JSON support, so you can do the entire conversion with AR:

    >> require 'active_support/all' #=> true
    >> json = {'foo'=>'bar'}.to_json #=> "{"foo":"bar"}"
    >> ActiveSupport::JSON.decode(json).to_xml #=> "\n\n  bar\n\n"
    

    The first line loads in the XML and JSON conversions. The second line sets up a JSON sample to use for testing. The third line takes the pretend JSON, decodes it, then converts it to XML.

提交回复
热议问题