Reputation: 2442
I need to write the xml i get from the function below to a file. Can someone help me finish this code:
import json
import urllib
results = json.load(urllib.urlopen("http://www.kimonolabs.com/api/4v1t8lgk?apikey=880a9bdbfb8444e00e2505e1533970a7"))
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))
f= open('tori_json.xml', 'w')
f.write(str(json_obj))
f.close()
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)
So when i run the function json2xml(results) it would write the xml to file.
Upvotes: 0
Views: 461
Reputation: 3098
This code uses BeautifulSoup. The JSON structure needs a little extra information for it to be a decent XML, so I added some 'product' tags to encapsulate each product.
from copy import deepcopy
import json
import re
import urllib
from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString
results = json.load(urllib.urlopen("http://www.kimonolabs.com/api/4v1t8lgk?apikey=880a9bdbfb8444e00e2505e1533970a7"))
class named_list(list):
def __init__(self, name, *args, **kwargs):
self.name = name
super(named_list, self).__init__(*args, **kwargs)
def __repr__(self):
return "<named_list %s: %s>" % (self.name, super(named_list, self).__repr__())
def dict_recurse(obj, obj_parent, nameless_default = "product"):
olist = []
if isinstance(obj, list):
for x in obj:
olist.extend(dict_recurse(x, obj))
elif isinstance(obj, dict):
for x in sorted(obj.keys()):
olist.append(named_list(x, dict_recurse(obj[x], obj)))
if isinstance(obj_parent, list):
olist = [named_list(nameless_default, olist)]
else:
olist.append(obj)
return olist
def tag_tree_build(ilist, top_tag, soup):
if isinstance(ilist, named_list):
cur_tag = Tag(soup, ilist.name)
for q in ilist:
tag_tree_build(q, cur_tag, soup)
top_tag.insert(len(top_tag), cur_tag)
elif isinstance(ilist, list):
for q in ilist:
tag_tree_build(q, top_tag, soup)
else:
cur_str = NavigableString(re.sub("\s+", " ", unicode(ilist)))
top_tag.insert(len(top_tag), cur_str)
nested = dict_recurse(results, results)
soup = BeautifulStoneSoup()
tag_tree_build(nested, soup, soup)
file("finnish.xml", "w").write(soup.prettify())
file("finnish.json", "w").write(json.dumps(results, sort_keys = True, indent = 4))
Upvotes: 0
Reputation: 180532
with open("data.xml",'w') as f:
for line in json2xml(results):
f.write(line.encode('utf-8'))
probably better using some xml processing lib
Upvotes: 1