Exemplo n.º 1
0
def save_xml_file(filename):
    with open(filename, "w") as write_file:
        xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"aqi.xsl\"?>\n"
        data = readfromjson("aqi.json")
        aqi_xml = json2xml.Json2xml(data).to_xml()
        write_file.write(xmlHeader)
        write_file.write(aqi_xml)
        print("The file {0} was successfully created.".format(filename))
Exemplo n.º 2
0
def convert_json_to_xml(filename):
    output_file_name = filename.split('.')[-2]
    if '/' in output_file_name:
        output_file_name = output_file_name.split('/')[-1]
    output_file_name += "_" + str(int(random.random() * 10000)) + ".xml"
    data = readfromjson(filename)
    fob = open(output_file_name, 'w')
    fob.write(json2xml.Json2xml(data).to_xml())
    fob.close()
    print("XML file was created, filename= ", output_file_name)
    return output_file_name
Exemplo n.º 3
0
def jsontoxml():
    cdir=os.getcwd()
    outdir='annotations'
    for directory in ['data/train']:#,'data/test']:
        if not os.path.exists(os.path.join(cdir,directory,outdir)):
            os.mkdir('{}/{}/{}'.format(cdir,directory,outdir))
            ##
        for files in os.listdir(os.path.join(cdir,directory,'json')):
            if files.endswith('.json'):
                data=readfromjson(os.path.join(cdir,directory,'json',files))
                xml=json2xml.Json2xml(data).to_xml()
                name=files.replace('.json','.xml')
                txt_file= open(os.path.join(cdir,directory,outdir,name),'w')
                txt_file.write(xml)
                txt_file.close()
def convert_file(filepath):
    '''Converts given filename from json to xml

    :param filepath: path to file to convert. It supposed to exist
    :type filepath: str

    :returns: converted xml or None if any input was not valid
    :rtype: str or None
    '''
    print(f"Processing {filepath}")
    xml_data = None
    try:
        json_data = readfromjson(filepath)
        xml_data = json2xml.Json2xml(json_data).to_xml()
    except SystemExit:
        print(f"Unable to convert {filepath}. Check if it is valid json")
    return xml_data
Exemplo n.º 5
0
def json_to_xml() -> bool:
    '''
  Converts json to xml
  return -> bool
  '''
    try:
        # Data should be written appended to a file with correct xml header
        # An xsl file should have all html/css stlying to render data from xml
        xml_header = '<?xml version="1.0"?>' + "\n" + '<?xml-stylesheet type="text/xsl" href="aqi.xsl"?>' + "\n"
        json_data = readfromjson("aqi.json")
        #print(json2xml.Json2xml(json_data).to_xml())
        xml_data = json2xml.Json2xml(json_data).to_xml()
        filename = "aqi.xml"
        FileIO.xml2file(xml_header, filename)
        FileIO.append_xml2file(xml_data, filename)
        return True
    except:
        return False
Exemplo n.º 6
0
 def save(self, **kwargs):
     path=settings.MEDIA_ROOT
     file_format_now=self.file_format
     file_format_change_to=self.format_output
     super().save()
     file_name = self.document.name
     print(file_name)
     file = path+'/'+file_name
     print(file)
     name=file.split('.')[0]
     print(name)
     if file_format_now == 'json' and file_format_change_to == 'xml' :
         data=readfromjson(file)
         with open(file, 'w') as f:
              myfile = File(f)
              myfile.write(json2xml.Json2xml(data).to_xml())
         myfile.closed
         os.rename(file,name+'.xml')
Exemplo n.º 7
0
    def save2dir(self, output_dir=None):
        try:
            if output_dir is None:
                if self.device.output_dir is None:
                    return
                else:
                    output_dir = os.path.join(self.device.output_dir, "states")
            if not os.path.exists(output_dir):
                os.makedirs(output_dir)
            # new line
            from json2xml import json2xml, readfromjson
            dest_state_self_path = "%s/state_%s.xml" % (output_dir, self.tag)
            dest_state_json_path = "%s/state_%s.json" % (output_dir, self.tag)
            if self.device.adapters[self.device.minicap]:
                dest_screenshot_path = "%s/screen_%s.jpg" % (output_dir,
                                                             self.tag)
            else:
                dest_screenshot_path = "%s/screen_%s.png" % (output_dir,
                                                             self.tag)
            dest_videorecord_path = "%s/screen_%s.mp4" % (output_dir, self.tag)
            state_json_file = open(dest_state_json_path, "w")
            state_json_file.write(self.to_json())
            state_json_file.close()
            # new line
            data = readfromjson(dest_state_json_path)
            state_xml_file = open(dest_state_self_path, "w")
            state_xml_file.write(json2xml.Json2xml(data).to_xml())
            state_xml_file.close()

            import shutil
            shutil.copyfile(self.screenshot_path, dest_screenshot_path)
            self.screenshot_path = dest_screenshot_path
            shutil.copyfile(self.videorecord_path, dest_videorecord_path)
            self.videorecord_path = dest_videorecord_path

            # from PIL.Image import Image
            # if isinstance(self.screenshot_path, Image):
            #     self.screenshot_path.save(dest_screenshot_path)
        except Exception as e:
            self.device.logger.warning(e)
Exemplo n.º 8
0
"""from json2xml import json2xml,readfromjson

data = readfromjson("358448 k.kavya 20180323 15-30-00.json")
xml=json2xml.Json2xml(data).to_xml()
print(xml)"""

import os
from json2xml import json2xml, readfromjson
cdir = os.getcwd()
outdir = 'annotations'
import pdb

for directory in ['data/train', 'data/test']:
    if not os.path.exists(os.path.join(cdir, directory, outdir)):
        os.mkdir('{}/{}/{}'.format(cdir, directory, outdir))
        #pdb.set_trace()
    for files in os.listdir(os.path.join(cdir, directory, 'json')):
        if files.endswith('.json'):
            data = readfromjson(os.path.join(cdir, directory, 'json', files))
            xml = json2xml.Json2xml(data).to_xml()
            name = files.replace('.json', '.xml')
            txt_file = open(os.path.join(cdir, directory, outdir, name), 'w')
            txt_file.write(xml)
            txt_file.close()
Exemplo n.º 9
0
from json2xml import json2xml, readfromjson

data = readfromjson("/home/spider/Downloads/example_2.json")

data = json2xml.Json2xml(data).to_xml()

with open('output.txt', 'w+') as f:
    f.write(data)
os.remove("url")
Exemplo n.º 10
0
from json2xml import json2xml, readfromurl, readfromstring, readfromjson

# get the xml from an URL that return json
data = readfromurl("https://coderwall.com/vinitcool76.json")
print(json2xml.Json2xml(data).to_xml())
print('-----------------------------------------')

# get the xml from a json string
data = readfromstring(
    '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}'
)
print(json2xml.Json2xml(data, wrapper="custom", indent=8).to_xml())
print('-----------------------------------------')

# get the data from an URL
# check for empty
data = readfromjson("example.json")
print(json2xml.Json2xml(data).to_xml())
print('-----------------------------------------')
def json_2_xml_jsonfile(jsonFileName):
    data_txt = readfromjson(jsonFileName)
    data_txt_xml = json2xml.Json2xml(data_txt).to_xml()
    print(data_txt_xml)
Exemplo n.º 12
0
 def test_read_from_invalid_json(self):
     """Test something."""
     with pytest.raises(SystemExit) as pytest_wrapped_e:
         data = readfromjson("examples/licht_wrong.json")
     assert pytest_wrapped_e.type == SystemExit
Exemplo n.º 13
0
 def test_read_from_json(self):
     """Test something."""
     data = readfromjson("examples/licht.json")
     assert type(data) is dict
Exemplo n.º 14
0
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 10:44:54 2019

@author: Sabeshnav M
"""

from json2xml import json2xml, readfromurl, readfromstring, readfromjson
"""# get the xml from an URL that return json
data = readfromurl("https://dataturks.com/projects/devika.mishra/face_detection")
print(json2xml.Json2xml(data).to_xml())
# get the xml from a json string
data = readfromstring(
    '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}'
)
print(json2xml.Json2xml(data).to_xml())"""

# get the data from an URL
data = readfromjson(
    "https://dataturks.com/projects/devika.mishra/face_detection")
print(json2xml.Json2xml(data).to_xml())