繁体   English   中英

将 xml 转换为 json 用于 Mongo db

[英]Converting xml to json for Mongo db

我目前正在尝试将具有大约 2k 条记录的 xml 文档转换为 json 以上传到 Mongo DB。 我已经为转换编写了一个 python 脚本,但是当我将其上传到 Mongo db 时,该集合将其作为一个文档读取,其中包含 2k 个子 arrays(对象),但我试图获取 2k 个文档。 我的想法是它可能是 python 代码吗? 任何人都可以帮忙。

# Program to convert an xml
# file to json file

# import json module and xmltodict
# module provided by python
import json
import xmltodict


# open the input xml file and read
# data in form of python dictionary
# using xmltodict module
with open("test.xml") as xml_file:
    
    data_dict = xmltodict.parse(xml_file.read())
    # xml_file.close()
    
    # generate the object using json.dumps()
    # corresponding to json data
    
    json_data = json.dumps(data_dict)
    
    # Write the json data to output
    # json file
    with open("data.json", "w") as json_file:
        json_file.write(json_data)
        # json_file.close()

我不知道为什么您会期望 XML 到 JSON 转换器在“记录”边界处自动拆分 XML。 毕竟,XML 没有内置的“记录”概念——这是你词汇的语义,而不是 XML 的语法。

将 XML 文件拆分为多个文件的最简单方法是使用简单的 XSLT 2.0+ 样式表。 如果您使用 XSLT 3.0,那么您可以同时调用 JSON 转换。

这是我的解决方案。

import xmltodict
import json
import pprint
# Open xml file
with open(r"test.xml", "rb") as xml_file:
    # data_dict = xmltodict.parse(xml_file.read())
    dict_data = xmltodict.parse(xml_file)

output_data = dict_data["root"]["course_listing"]

json_data = json.dumps(output_data, indent=2)
print(json_data)

with open("datanew.json", "w") as json_file:
    json_file.write(json_data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM