Loop only reads 1st line of file
<p>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. </p>

<pre><code>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&lt;%s&gt;" % (line_padding, tag_name))
        result_list.append(json2xml(sub_obj, "\t" + line_padding))
        result_list.append("%s&lt;/%s&gt;" % (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
</code></pre>

<p>def converter(data):</p>

<pre><code>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)
</code></pre>

<p>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. </p>

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

<pre><code>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
</code></pre>

python json xml loops