将XML转JSON导入MongoDB:如何生成2000个独立文档?
问题:XML转JSON后MongoDB识别为单个文档,需拆分为独立文档
我有一份含约2000条记录的XML文档,需要转换为JSON格式后上传至MongoDB。当前使用以下Python脚本转换后,MongoDB将其识别为包含2000个子对象的单个文档,但我需要生成2000个独立文档。怀疑问题出在转换代码上,求解决。
原代码:
# 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对象,导致MongoDB把整个JSON文件当成一个文档。要生成2000个独立文档,需要遍历XML中的每条记录,将每个记录单独序列化为JSON对象,以JSON Lines格式(每行一个独立JSON)写入文件。
修改后的代码
import json import xmltodict # 读取并解析XML文件为Python字典 with open("test.xml") as xml_file: data_dict = xmltodict.parse(xml_file.read()) # 关键:根据你的XML实际结构,定位到记录列表 # 示例:如果XML结构是 <dataset><record>...</record><record>...</record></dataset> # 则改为 records = data_dict["dataset"]["record"] # 请务必根据自己的XML节点名称调整这一行 records = data_dict["你的根节点名称"]["你的记录节点名称"] # 以JSON Lines格式写入文件,每个记录占一行 with open("data.json", "w") as json_file: for record in records: # 将单个记录转为JSON字符串,写入文件时换行 json_line = json.dumps(record) json_file.write(json_line + "\n")
注意事项
- 调整节点路径:必须根据你的XML实际结构修改
records的取值路径,比如XML根节点是data,每条记录的节点是item,就写成data_dict["data"]["item"]。如果不确定结构,可以先打印data_dict查看层级。 - MongoDB导入:生成的
data.json是JSON Lines格式,可直接用mongoimport批量导入:mongoimport --db 你的数据库名 --collection 你的集合名 --file data.json
内容的提问来源于stack exchange,提问作者user19485723
相关产品推荐
相关产品推荐

