【发布时间】:2016-10-15 14:25:47
【问题描述】:
我正在尝试使用一个小的 python 脚本将 JSON 文件转换为 XML,但由于某种原因,循环似乎只读取了 JSON 文件的第一行。
from xml.dom import minidom
from json import JSONDecoder
import json
import sys
import csv
import os
import re
import dicttoxml
from datetime import datetime, timedelta
from functools import partial
reload(sys)
sys.setdefaultencoding('utf-8')
nav = 'navigation_items.bson.json'
df = 'testxmloutput.txt'
def json2xml(json_obj, line_padding=""):
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding))
return "\n".join(result_list)
if json_obj_type is dict:
for tag_name in json_obj:
sub_obj = json_obj[tag_name]
result_list.append("%s<%s>" % (line_padding, tag_name))
result_list.append(json2xml(sub_obj, "\t" + line_padding))
result_list.append("%s</%s>" % (line_padding, tag_name))
return "\n".join(result_list)
return "%s%s" % (line_padding, json_obj)
def json_parse(fileobj, decoder=JSONDecoder(), buffersize=2048):
buffer = ''
for chunk in iter(partial(fileobj.read, buffersize), ''):
buffer += chunk
while buffer:
try:
result, index = decoder.raw_decode(buffer)
yield result
buffer = buffer[index:]
except ValueError:
# Not enough data to decode, read more
break
def 转换器(数据):
f = open(df,'w')
data = open(nav)
for line in json_parse(data):
f.write(dicttoxml.dicttoxml(line, attr_type=False))
f.close()
converter(nav)
我假设迭代器会将第一行读入内存并继续下一行。转换后的输出看起来很棒,但我太确定在哪里查看如何让它循环到文件中的下一行。
【问题讨论】:
-
如果你放弃 iter 包装会发生什么?
-
它执行相同的操作。我想知道我是否以某种方式否定了任何级别的循环动作。
-
什么是
json_parse()?它似乎不是来自标准库。 -
抱歉...添加了整个代码。