【问题标题】:Loop only reads 1st line of file循环只读取文件的第一行
【发布时间】: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()?它似乎不是来自标准库。
  • 抱歉...添加了整个代码。

标签: python json xml loops


【解决方案1】:

尝试 json.load 将文件加载到 dict 中,然后迭代 dict 以获得输出。

import sys
import json

json_file = sys.argv[1]
data = {}
with open(json_file) as data_file:    
    data = json.load(data_file)

for key in data:
    #do your things

【讨论】:

  • 终于找到了答案。原来我使用的文件是问题所在。我需要在我的 json 集周围加上括号才能看到其他行。但是你的回答也帮助我更好地理解了interables!
猜你喜欢
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2018-03-22
  • 2011-10-25
  • 2018-09-05
  • 1970-01-01
  • 2021-06-30
  • 2019-12-16
相关资源
最近更新 更多