def test_json_to_xml_conversion(self): data = readfromstring( '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}' ) xmldata = json2xml.Json2xml(data).to_xml() dict_from_xml = xmltodict.parse(xmldata) assert type(dict_from_xml["all"]) == OrderedDict
def json_2_xml_str(dataStr): try: data = readfromstring(dataStr) data_xml = json2xml.Json2xml(data).to_xml() print(data_xml) except: print("an error occured")
def test_custom_wrapper_and_indent(self): data = readfromstring( '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}' ) xmldata = json2xml.Json2xml(data, wrapper="test", indent=8).to_xml() old_dict = xmltodict.parse(xmldata) # test must be present, snce it is the wrpper assert "test" in old_dict.keys() # reverse test, say a wrapper called ramdom won't be present assert "random" not in old_dict.keys()
def conv(csvFile, xmlFile): with open(csvFile, "r") as cf: fieldnames = tuple(cf.readline().split(',')) reader = csv.DictReader(cf, fieldnames) json_csv = json.dumps([row for row in reader]) with open(xmlFile, "w") as xf: insertHeader() data = readfromstring(json_csv) xf.write(json2xml.Json2xml(data, wrapper="row", indent=4).to_xml())
def save_json_xml(TEST_IMAGE_FOLDER, IMAGES_FOLDER_NAME, folder, category_index, image_path, output_dict): img = cv2.imread(os.path.join(TEST_IMAGE_FOLDER, image_path)) image_height, image_width, depth = img.shape out_dict = { 'folder': IMAGES_FOLDER_NAME, 'filename': image_path, 'path': os.path.join(TEST_IMAGE_FOLDER, image_path), 'size': { 'width': image_width, 'height': image_height, 'depth': depth } } for index, score in enumerate(output_dict['detection_scores']): if score < 0.3: continue label = category_index[output_dict['detection_classes'][index]]['name'] ymin, xmin, ymax, xmax = output_dict['detection_boxes'][index] out_dict.update({ 'object' + str(index + 1): { 'name': label, 'bndbox': { 'xmin': int(xmin * image_width), 'ymin': int(ymin * image_height), 'xmax': int(xmax * image_width), 'ymax': int(ymax * image_height) } } }) data = readfromstring(json.dumps(out_dict)) s = json2xml.Json2xml(data, wrapper="annotation").to_xml() s = re.sub("object\d+", 'object', s) fname = os.path.splitext(image_path)[0] OUTPUT_FOLDER_XML = os.path.join(folder, OUTPUT_DIR_XML) OUTPUT_FOLDER_JSON = os.path.join(folder, OUTPUT_DIR_JSON) # create dir for storing xml if not os.path.exists(OUTPUT_FOLDER_XML): os.makedirs(OUTPUT_FOLDER_XML) # create dir for storing json if not os.path.exists(OUTPUT_FOLDER_JSON): os.makedirs(OUTPUT_FOLDER_JSON) with open(os.path.join(OUTPUT_FOLDER_XML, fname + '.xml'), 'w') as output: output.write(s) output.close() with open(os.path.join(OUTPUT_FOLDER_JSON, fname + '.json'), 'w') as out: out.write(str(output_dict)) out.close()
def exportTimetable(): # print(request) if not request.json: return ("error") data = request.json result = helper.fitOrderToData(data) # print("\n\n", data, "\n\n", result) # return "hello" id = data["key"] filePath = "./finalResult/" + id + "/" + id + "." + data["fileType"] if not os.path.exists(os.path.dirname(filePath)): try: os.makedirs(os.path.dirname(filePath)) except OSError as exc: # Guard against race condition return ("error") finalData = "" if (data["fileType"] == "xml"): jsonData = readfromstring(dumps(result)) finalData = json2xml.Json2xml(jsonData).to_xml() elif (data["fileType"] == "html"): finalData = json2html.convert(json=helper.fitDataToHtml(result)) with open(filePath, "w") as fh: fh.write(finalData) fh.close() # print(helper.fitDataToHtml(result)) # return "hello" # body = { # "fileType":data["fileType"], # "name":result["name"], # "data":finalData # } # resp = Response(dumps(body), status=200, mimetype='application/json') # print(data) return send_file("." + filePath)
def run(self, text): from json2xml import json2xml, readfromstring return json2xml.Json2xml(readfromstring(text)).to_xml()
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('-----------------------------------------')
import json from json2xml import json2xml, readfromurl, readfromstring, readfromjson import xmltodict fh = open("mouse_log.txt", "r") json_data = {} json_data["mouseActions"] = [] while True: line = fh.readline() if ("" == line): print("file finished") break lis = line.split(" ", 2) json_data["mouseActions"].append({ 'date': lis[0], 'time': lis[1], 'action': lis[2] }) json_str = json.dumps(json_data) print(json_str) f = open("jsonfile.json", 'w+') f.write(json_str) data = readfromstring(json_str) fe = open("Xmlfile.xml", 'w+') data1 = json2xml.Json2xml(data, wrapper="custom", indent=8).to_xml() fe.write(data1)
def socket_init(): logging.debug("entering socket_test function") # OPEN SOCKET STREAM sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # BIND SOCKET TO PORT AND HOST sock.bind((host,port)) #SOCKET IS IN LISTENING MODE sock.listen() logging.debug(sock.getpeername) #print(sock.getpeername) while True: #SOCKET IS ACCEPTING DATA FROM INCOMING CONN conn,addr =sock.accept() print("connected by",addr) logging.debug("socket is accepting data") #CONVERT DATA from bytestream to string data=conn.recv(1024) data = data.decode("utf-8") logging.debug("data is deserialized to utf-8") print("received data:",data) #scrape data that fits the regex rule which is only json print ("\n regex step \n") only_json_data = regex_test(data) print(only_json_data) logging.debug("data is parsed to scrape only json data from post request") #after regexing, our data is converted to list, we need to convert it back to string to parse it again to xml print("\n list to string conversion step") only_json_data_str = list_to_string_after_regex(only_json_data) print(only_json_data_str) logging.debug("list is converted to str \n") # convert string json to pretty xml to work with it print("\n json to xml conversion step \n") final_data = readfromstring(only_json_data_str) final_data_xml = json2xml.Json2xml(final_data).to_xml() print(final_data_xml) #final data is assigned to variable tomconn_post_data = final_data_xml print("\n final data is converted to xml and assigned to global variable \n") print("\n TESTTTT !!! \n") print(tomconn_post_data,dest_url,api_key) #get current time #func_timer = datetime.now().time() api_caller(tomconn_post_data,dest_url,api_key) conn.close()
def test_read_from_invalid_jsonstring(self): with pytest.raises(SystemExit) as pytest_wrapped_e: data = readfromstring( '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"' ) assert pytest_wrapped_e.type == SystemExit
def test_read_from_jsonstring(self): data = readfromstring( '{"login":"******","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}' ) assert type(data) is dict