2016-10-15 13 views
0

小さなPythonスクリプトを使用してJSONファイルをXMLに変換しようとしていますが、何らかの理由でループがJSONファイルの最初の行を読み取っているようです。ループはファイルの第1行だけを読み取る

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は、メモリへの最初のラインを読み、次へ移動するという仮定の下にありました。変換された出力は素晴らしいように見えますが、ファイル内の次の行にループする方法を調べる場所はあまりにも確かです。

+0

iterラッピングを削除するとどうなりますか? –

+0

同じアクションを実行します。私は何らかのレベルのループアクションを否定しているのだろうかと思います。 – hscorpio15201

+0

'json_parse()'とは何ですか?それは標準ライブラリからのものではないようです。 – martineau

答えて

0

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 
+0

最後に答えを見つけました。私が使用していたファイルが問題だったことが分かります。他の行を見るために私のjsonの周りに括弧が必要です。しかし、あなたの答えはまた、私の理解しやすい仲間を少し良くするのを助けました! – hscorpio15201

関連する問題