Skip to content

Instantly share code, notes, and snippets.

@MishraKhushbu
Last active August 7, 2019 10:50
Show Gist options
  • Save MishraKhushbu/bf4b9112cda58238f5c2f5aea38102bc to your computer and use it in GitHub Desktop.
Save MishraKhushbu/bf4b9112cda58238f5c2f5aea38102bc to your computer and use it in GitHub Desktop.
JSON_TO_XML
import json
def json2xml(str_json): # function to convert json to xml
global my_str_startswith
global my_str_endswith
global mid_str_list
for items in str_json:
my_str_startswith = "<" + items + ">" #gives starting tag like <tag>
print(my_str_startswith)
if type(str_json[items]) is dict: #checks whether the key of the dict is again a dictionary or not
json2xml(str_json[items]) #if key is dict , repeats it in loop
elif type(str_json[items]) is list: #the key holds a single value or list
for i in range(len(str_json[items])):
if (type(str_json[items][i])) != dict:
mid_str_dict = str(str_json[items][i])
print(mid_str_dict)
else:
json2xml(str_json[items][i])
else:
mid_str_dict = "<" + str(str_json[items]) + ">"
print(mid_str_dict)
my_str_endswith = "<\>" + items + ">" #gives end of tag like <\tag>
print(my_str_endswith)
with open("sample.json") as f0: #opens sample_json file and and loads it.
str_json = json.load(f0)
json2xml(str_json) #calling the json2xml function
#soup = BeautifulSoup(contents , 'xml')
#print(soup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment