如何将给定XML Payload转换为指定结构的JSON输出?
XML转指定结构JSON的实现
输入XML Payload
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <item> <item_status>2</item_status> <item_number>null</item_number> <details> <order_flag> <tag>0000</tag> <item_line> <item_quantity>10</item_quantity> <count>1</count> </item_line> <item_line> <item_quantity>8</item_quantity> <count>5</count> </item_line> </order_flag> <order_flag> <tag>1111</tag> <item_line> <item_quantity>15</item_quantity> <count>2</count> </item_line> <item_line> <item_quantity>25</item_quantity> <count>3</count> </item_line> </order_flag> </details> </item>
期望输出JSON
{ "item_status": "2", "item_number": null, "order_flag": { "tag": "0000", "item_line": [ { "item_quantity":"10", "count":"1", "brand": "null" }, { "item_quantity":"8", "count":"5", "brand": "null" } ] }, "order_flag":{ "tag":"1111", "item_line":[ { "item_quantity":"15", "count":"2", "brand": "null" }, { "item_quantity":"25", "count":"3", "brand": "null" } ] } }
实现思路与代码
注意:目标JSON存在重复的order_flag键,这不符合JSON规范(常规解析工具会用后出现的键覆盖前一个),但按需求实现。以下用Python结合xmltodict库完成转换:
- 安装依赖
pip install xmltodict
- 转换代码
import xmltodict # 输入XML内容 xml_content = """<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <item> <item_status>2</item_status> <item_number>null</item_number> <details> <order_flag> <tag>0000</tag> <item_line> <item_quantity>10</item_quantity> <count>1</count> </item_line> <item_line> <item_quantity>8</item_quantity> <count>5</count> </item_line> </order_flag> <order_flag> <tag>1111</tag> <item_line> <item_quantity>15</item_quantity> <count>2</count> </item_line> <item_line> <item_quantity>25</item_quantity> <count>3</count> </item_line> </order_flag> </details> </item> """ # 解析XML为字典结构 xml_dict = xmltodict.parse(xml_content)['item'] # 构建基础JSON字符串 json_str = f"""{{ "item_status": "{xml_dict['item_status']}", "item_number": {None if xml_dict['item_number'] == 'null' else f'"{xml_dict["item_number"]}"'}, """ # 遍历每个order_flag,拼接对应JSON片段 for flag in xml_dict['details']['order_flag']: # 处理当前flag下的item_line line_fragments = [] for line in flag['item_line']: line_frag = f""" {{ "item_quantity":"{line['item_quantity']}", "count":"{line['count']}", "brand": "null" }}""" line_fragments.append(line_frag) # 拼接当前order_flag的完整片段 flag_frag = f""" "order_flag":{{ "tag":"{flag['tag']}", "item_line":[ {',\n'.join(line_fragments)} ] }}""" json_str += flag_frag + ',\n' # 清理末尾逗号并闭合JSON结构 json_str = json_str.rstrip(',\n') + '\n}' # 输出结果 print(json_str)
关键说明
- 由于JSON规范不允许对象存在重复键,常规
json.dumps方法会自动覆盖重复键,因此采用手动拼接字符串的方式保留重复的order_flag。 - 将XML中字符串类型的
"null"转换为JSON原生的null值。 - 为每个
item_line对象补充了brand字段,值固定为"null"。
内容的提问来源于stack exchange,提问作者james11
相关产品推荐
相关产品推荐

