【问题标题】:convert json to xml without changing the order of parameters in python在不改变python中参数顺序的情况下将json转换为xml
【发布时间】:2015-09-23 02:43:25
【问题描述】:

我正在使用 Json2xml 模块将 json 格式转换为 xml 格式。但是,在转换它时会改变参数的顺序。如何在不更改参数顺序的情况下进行转换?这是我的python代码。

from json2xml.json2xml import Json2xml

data = Json2xml.fromjsonfile('example.json').data
data_object = Json2xml(data)
xml_output = data_object.json2xml()
print xml_output

example.json

{
    "action": {
      "param1": "aaa",
      "param2": "bbb"
    }
}

输出是

<action>
<param2>bbb</param2>
<param1>aaa</param1>
</action>

有没有办法在不改变参数顺序的情况下将json转为xml?

【问题讨论】:

    标签: python json xml


    【解决方案1】:

    尝试使用OrderedDict

    from collections import OrderedDict
    from json2xml.json2xml import Json2xml
    
    data = Json2xml.fromjsonfile('example.json').data
    data = OrderedDict(data)
    data_object = Json2xml(data)
    xml_output = data_object.json2xml()
    print xml_output
    

    【讨论】:

    • 有什么区别?我不希望对项目进行排序。我只希望它们与 json 中的顺序相同。
    • 如果您在example.json 中切换元素的顺序,您将在输出的 XML 中看到顺序变化
    猜你喜欢
    • 2017-08-04
    • 2014-03-29
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多