- Jul 27, 2006
- 628
- 3
- 81
Hey Guys,
Could use a second pair of eyes on a small python script to convert JSON to XML. I've been looking at this all day and cant seem to get it to run past the first line of the json file I'm trying to convert. It converts the first line beautifully but doesn't seem to go past it. I think it has to do with the for statement but I hit the wall. Any hints would help!
Sean
Could use a second pair of eyes on a small python script to convert JSON to XML. I've been looking at this all day and cant seem to get it to run past the first line of the json file I'm trying to convert. It converts the first line beautifully but doesn't seem to go past it. I think it has to do with the for statement but I hit the wall. Any hints would help!
Sean
Code:
from xml.dom.minidom import Document
from json import JSONDecoder
import dicttoxml
import json
import bson
#from bson import BSONdecoder
#BSONdecoder().decode('{}')
from functools import partial
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
nav = 'navigation_items.bson.json'
df = 'butt1.txt'
class DictToXMLtest(object):
default_list_item_name = "item"
def __init__(self, structure, list_mappings={}):
self.doc = Document()
if len(structure) == 1:
rootName = str(list(structure.keys())[0])
self.root = self.doc.createElement(rootName)
self.list_mappings = list_mappings
self.doc.appendChild(self.root)
self.build(self.root, structure[rootName])
def build(self, father, structure):
if type(structure) == dict:
for k in structure:
tag = self.doc.createElement(k)
father.appendChild(tag)
self.build(tag, structure[k])
elif type(structure) == list:
tag_name = self.default_list_item_name
if father.tagName in self.list_mappings:
tag_name = self.list_mappings[father.tagName]
for l in structure:
tag = self.doc.createElement(tag_name)
self.build(tag, l)
father.appendChild(tag)
else:
data = str(structure)
tag = self.doc.createTextNode(data)
father.appendChild(tag)
def display(self):
print(self.doc.toprettyxml(indent=" "))
def get_string(self):
return self.doc.toprettyxml(indent=" ")
def json_parse(fileobj, decoder=JSONDecoder(), buffersize=16384):
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
if __name__ == '__main__':
ifile = open(nav,'r')
nfile = open(df,'w')
data = {}
with ifile as data_file:
data = (data_file)
for line in json_parse(data):
nfile.write(dicttoxml.dicttoxml(line, attr_type=False))
nfile.close()