【问题标题】:How to prevent same name XML tags being converted to Array when converting the XML String to JSON using Python?使用 Python 将 XML 字符串转换为 JSON 时,如何防止同名 XML 标记转换为数组?
【发布时间】:2018-10-05 09:04:15
【问题描述】:

我有一个格式如下的 XML 文件 -

<root>
   <tag>
   This is the first Value.
   </tag>
   <tag>
   This is the second Value.
   </tag>
</root>

当我使用以下代码在 Python 中将此 XML 字符串转换为 JSON 时

jsonString=json.dumps(XML_String)

标签变成数组,我得到的JSON文件是这样的——

{"root":["tag":"This is the first Value",
         "tag":"This is the second Value"]}

我真正想要的是&lt;root&gt; 标签应该是一个对象而不是一个数组。像这样——

{"root":{"tag":"This is the first Value",
         "tag":"This is the second Value"}}

如何实现这种格式?

【问题讨论】:

    标签: python json xml mongodb parsing


    【解决方案1】:

    您要生成的是无效的 JSON。

    好吧,也许不是完全无效,但至少与良好做法相反:RFC 8259 说:“当对象中的名称不唯一时,接收此类对象的软件的行为是不可预测的。许多实现报告最后仅限名称/值对。其他实现会报告错误或无法解析对象,并且某些实现会报告所有名称/值对,包括重复项。”

    所以不要这样做。

    【讨论】:

      【解决方案2】:

      我通过创建自定义 JSON 字符串解决了这个问题。它确实奏效了。未创建数组。

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 2020-02-20
        • 2016-03-17
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2017-08-05
        • 2017-05-04
        • 1970-01-01
        相关资源
        最近更新 更多