简体   繁体   中英

Loop only reads 1st line of file

I'm trying to convert a JSON file to XML using a small python script, but for some reason the loop only seems to read the first line of the JSON file.

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 converter(data):

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)

I was under the assumption that the iter would read the first line to memory and move on to the next. The converted output looks great but im too sure where to look on how to get it to loop through to the next line in file.

Try json.load to load the file into a dict and then iterate the dict for your output.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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