def AppendGlossaryEntriesToFile(fileName): try: newKey = input("Enter a word you'd like to define:\n") newValue = input("Enter the definition:\n") newEntry = { newKey : newValue} with open(filename, "r+") as append_file: finalEntry = jsonLoad(append_file) finalEntry.update(newEntry) append_file.seek(0) jsonDump(finalEntry, append_file, indent = 4, sort_keys=True) except Exception as ex: print("An error occured--------------------") print(ex) else: print("Entry added")
def _makeJson(request, do_method, option={}): ''' do_methodを実行し、JSON/JSONP形式のレスポンスを含んだ HttpResponseオブジェクトを返す do_methodは requestを引数に取り JSONに変換可能なオブジェクトを返す 関数である必要がある ''' DOMAIN = "http://%s" %(request.META["SERVER_NAME"], ) def to_json(obj): if isinstance(obj, ndb.Model): data = obj.to_dict() data["id"] = obj.key.id() if hasattr(obj, "created_at"): data["created_at"] = str(utils.jst_date(obj.created_at))[0:19] data["created_stamp"] = int(utils.timestamp(obj.created_at)) if hasattr(obj, "updated_at"): data["updated_at"] = str(utils.jst_date(obj.updated_at))[0:19] data["updated_stamp"] = int(utils.timestamp(obj.updated_at)) if hasattr(obj, "category"): data["category"] = arrays.get_category(obj.category) if hasattr(obj, "email"): del data["email"] return data result = do_method(request, option) response = jsonDump(result, default=to_json) if not apiform.callbackform(request.REQUEST).is_valid(): return HttpResponse(response) else : callback = request.REQUEST['callback'] return HttpResponse("%s(%s);"%(callback, response))
def save(): root = Tk() root.withdraw() filename = filedialog.asksaveasfilename( filetypes = [("JSON files", ".json"),("All files", "*")],defaultextension='.json') if filename: d = {'points':[], 'lines':[]} for ppp in range(1,len(Point.points)): p = Point.points[ppp] pd = { 'pos': {'x': p.pos.x, 'y': p.pos.y}, 'pinned' : p.pinned, 'size' : p.size, 'isMotor' : p.isMotor, 'spinPos': p.spinPos if p.spinPos == None else {'x': p.spinPos.x, 'y': p.spinPos.y}, 'spinSpeed' : p.spinSpeed, 'currentSpin' : p.currentSpin } d['points'].append(pd) for s in Stick.sticks: sd = { 'p1': save_helper_point_finder(s.p1), 'p2': save_helper_point_finder(s.p2), 'visible' : s.visible } d['lines'].append(sd) f = open(filename, 'w') f.write(jsonDump(d, indent = 4)) f.close()
def resToJson(input): res = {} res['restaurant'] = input[0] # Menu has to be a list - JSON can't preserve order otherwise res['menu'] = [] for [day, meals] in input[1].items(): res['menu'].append({'day': str(day), 'meals': meals}) return jsonDump(res)
def getBody(self) -> any: """ It returns a value that was set in the body Returns: any """ try: return jsonDump(self.body) if self.body is not None else "" except: return self.body
def __pushFile(self): self.oldFile = self.file self.file = {"data": self.db} try: with open(self.filePath, 'w') as file: file.write( jsonDump( self.file, indent=4 ) ) except Exception as error: with open(self.filePath, 'w') as file: file.write( jsonDump( self.oldFile, indent=4 ) ) raise error
def save(): root = Tk() root.withdraw() filename = filedialog.asksaveasfilename(filetypes=[("JSON files", ".json"), ("All files", "*")], defaultextension='.json') if filename: d = {'points': [], 'lines': []} for ppp in range(1, len(Point.points)): p = Point.points[ppp] pd = { 'pos': { 'x': p.pos.x, 'y': p.pos.y }, 'pinned': p.pinned, 'size': p.size, 'isMotor': p.isMotor, 'spinPos': p.spinPos if p.spinPos == None else { 'x': p.spinPos.x, 'y': p.spinPos.y }, 'spinSpeed': p.spinSpeed, 'currentSpin': p.currentSpin } d['points'].append(pd) for s in Stick.sticks: sd = { 'p1': save_helper_point_finder(s.p1), 'p2': save_helper_point_finder(s.p2), 'visible': s.visible } d['lines'].append(sd) f = open(filename, 'w') f.write(jsonDump(d, indent=4)) f.close()
def WriteGlossaryToFile(fileName): with open(fileName, "w") as write_file: jsonDump(lstWords, write_file, indent = 4, sort_keys=True)
print(pickleLoad(lectura)) except FileNotFoundError: with open('orellyPython/chapter9_x/p18_1.pkl',mode='wb') as f: pickleDump(tupla1,f) diccionario1=dict(raza='Rotwailer',nombre='Zeus') try : lectura=open('orellyPython/chapter9_x/p18_1.json',mode='r') print(jsonLoad(lectura)) lectura.close() except FileNotFoundError: with open('orellyPython/chapter9_x//p18_1.json',mode='w') as f: #LA SENTENCIA DESPUES DEL WITH puede ser declarada en fp,osea open(..) jsonDump(diccionario1,fp=f,indent=4) #print(jsonDumps(diccionario1,indent=4),file=f) #f.write(jsonDumps(diccionario1,indent=4)) #DELIMITADOR DE EXCEL ; #DELIMITADOR CSV , try : lectura=open('orellyPython/chapter9_x/p18_1.csv',mode='r') spamReader=reader(lectura, delimiter=';', quotechar='|') for row in spamReader: print(', '.join(row)) except FileNotFoundError: with open('orellyPython/chapter9_x/p18_1.csv',mode='w') as f: spamwriter = writer(f, delimiter=';',quotechar='|', quoting=QUOTE_MINIMAL) spamwriter.writerow(['Anime'] * 5) spamwriter.writerow(['Naruto', 'Shingeki', 'SAO','Death Note','FullMetal'])
verbose = True create = True if create: passdb = {} else: # mise a jour de la db pki passdb = encJson2dict(passDBfile) if not passdb['error']: passdb = passdb['message'] else: res = { "error": True, "message": "ERROR: Unable to read Serial database " + passDBfile + "." } print(res) exit(1) # ecriture dans la db passdb[name] = passph newjson = jsonDump(passdb, sort_keys=False) wresult = writeEncFile(passDBfile, newjson) if wresult['error']: res = {"error": True, "message": wresult['message']} print(res) exit(1) if verbose: print("INFO: Passphrases db file updated.")
modified = True if certname == 'cacert': critical = True res = { "error": True, "message": "ERROR: CA certificate is expired." } elif certname == 'intermediate_cacert': critical = True res = { "error": True, "message": "ERROR: Intermediate CA certificate is expired." } if critical: # return(res) print(res) exit(1) if modified: newjson = jsonDump(pkidb, sort_keys=False) wresult = writeFile(DBfile, newjson) if wresult['error']: res = {"error": True, "message": wresult['message']} # return(res) print(res) exit(1) if verbose: print("INFO: Pki db file updated.")