Python - 将超大 (6.4GB) XML 文件转换为 JSON

标签 python xml json

基本上,我有一个 6.4GB 的 XML 文件,我想将其转换为 JSON,然后将其保存到磁盘。我目前正在运行带有 i7 2700k 和 16GB 内存的 OSX 10.8.4,并运行 Python 64 位(双重检查)。我收到一个错误,指出我没有足够的内存来分配。我该如何解决这个问题?

print 'Opening'
f = open('large.xml', 'r')
data = f.read()
f.close()

print 'Converting'
newJSON = xmltodict.parse(data)

print 'Json Dumping'
newJSON = json.dumps(newJSON)

print 'Saving'
f = open('newjson.json', 'w')
f.write(newJSON)
f.close()

错误:

Python(2461) malloc: *** mmap(size=140402048315392) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Traceback (most recent call last):
  File "/Users/user/Git/Resources/largexml2json.py", line 10, in <module>
    data = f.read()
MemoryError

最佳答案

许多 Python XML 库支持增量解析 XML 子元素,例如标准库中的 xml.etree.ElementTree.iterparsexml.sax.parse。这些函数通常称为“XML 流解析器”。

您使用的 xmltodict 库也有流模式。我认为它可以解决您的问题

https://github.com/martinblech/xmltodict#streaming-mode

关于Python - 将超大 (6.4GB) XML 文件转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286118/

相关文章:

c# - C#和Python之间的进程间通信

java - 我希望 Spring Boot Java @Entity 模型类中的 String 成员变量之一在发送到客户端时显示为实际的 JSON 对象

api.stackexchange 上的 Java Http 请求和 json 响应

php - 你如何在 Laravel 的 json 响应中返回一个 View ?

python - n_support_(sklearn svm)中的类(class)顺序

python - 如何比较python中的两个列表并返回匹配项

python - 如何将 postman 的不记名 token 读入 Python 代码?

java - 将 Xml 请求转换为 Spring Boot 对象

c# - 当只有 xml 数据可用时,如何使用 LINQ to XML 插入新节点?

c# - 使用 XmlWriter 以迭代方式构建 XML 文件