Python json.write() Examples
The following are 7
code examples of json.write().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
json
, or try the search function
.
Example #1
Source File: lightmsg.py From talklog with MIT License | 5 votes |
def process_request(packet): pktlen=packet[0:4] cmd=packet[4] msg=eval(packet[5:]) msgjson=json.write(msg) yyyymm=time.strftime('%Y%m',time.localtime(msg['ts'])) if cmd=='i': #收件箱 filename=FILENAME_INBOX%{'month':yyyymm,} elif cmd=='t': #发件箱 filename=FILENAME_SENT%{'month':yyyymm,} else: print 'UNKNOWN:',repr(packet) return needwrite=False if os.path.exists(filename): ff=open(filename,'rU') for line in ff.xreadlines(): line=line.strip() if line==msgjson: needwrite=False break else: needwrite=True ff.close() else: needwrite=True if needwrite: ff=open(filename,'a+') ff.write(msgjson+'\n') ff.close() return
Example #2
Source File: pyjsontestrunner.py From OpenXR-SDK-Source with Apache License 2.0 | 5 votes |
def valueTreeToString(fout, value, path = '.'): ty = type(value) if ty is types.DictType: fout.write('%s={}\n' % path) suffix = path[-1] != '.' and '.' or '' names = value.keys() names.sort() for name in names: valueTreeToString(fout, value[name], path + suffix + name) elif ty is types.ListType: fout.write('%s=[]\n' % path) for index, childValue in zip(xrange(0,len(value)), value): valueTreeToString(fout, childValue, path + '[%d]' % index) elif ty is types.StringType: fout.write('%s="%s"\n' % (path,value)) elif ty is types.IntType: fout.write('%s=%d\n' % (path,value)) elif ty is types.FloatType: fout.write('%s=%.16g\n' % (path,value)) elif value is True: fout.write('%s=true\n' % path) elif value is False: fout.write('%s=false\n' % path) elif value is None: fout.write('%s=null\n' % path) else: assert False and "Unexpected value type"
Example #3
Source File: pyjsontestrunner.py From OpenXR-SDK-Source with Apache License 2.0 | 5 votes |
def rewriteValueTree(value, rewrite_path): rewrite = json.dumps(value) #rewrite = rewrite[1:-1] # Somehow the string is quoted ! jsonpy bug ? file(rewrite_path, 'wt').write(rewrite + '\n') return rewrite
Example #4
Source File: nlu_server.py From eywa with GNU General Public License v3.0 | 5 votes |
def save(self, path=None): if path is None: path = self.path if path is None: raise Exception('Path not provided!') with open(path, 'w') as f: json.write(self.get_config(), f)
Example #5
Source File: ipsms.py From talklog with MIT License | 4 votes |
def backup_month(start_tick,stop_tick,yyyymm): """备份一个月的短信""" conn=sqlite3.connect(DB_FILENAME) curr=conn.cursor() sql=SQL_GETSMS%{ 'start_tick':start_tick, 'stop_tick':stop_tick,} curr.execute(sql) dataset=curr.fetchall() curr.close() conn.close() savedset=set() if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}): fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r') fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r') for line in fr_inbox.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) for line in fr_sent.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) fr_inbox.close() fr_sent.close() msglist=[] fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+') fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+') for (starttime,flag,msg,addr) in dataset: msgdict={ 'msg':msg.encode('utf-8'), 'msgid':'%d-%s-%d'%(starttime, addr.encode('utf-8'),len(msg)), 'ts':starttime,} if msgdict['msgid'] in savedset: continue if flag==3: #sent msgdict['tfrom']=LOCAL_PHONENUMBER msgdict['to']=addr.encode('utf-8') fw_sent.write(json.write(msgdict)+'\n') elif flag==2: #inbox msgdict['tto']=LOCAL_PHONENUMBER msgdict['tfrom']=addr.encode('utf-8') fw_inbox.write(json.write(msgdict)+'\n') else: raise ValueError('Unknown flags=%d'%flags) fw_inbox.close() fw_sent.close() return
Example #6
Source File: n900mm.py From talklog with MIT License | 4 votes |
def backup_month(start_tick,stop_tick,yyyymm): """备份一个月的短信""" conn=sqlite3.connect(DB_FILENAME) curr=conn.cursor() sql=SQL_GETSMS%{ 'start_tick':start_tick, 'stop_tick':stop_tick,} #print sql curr.execute(sql) dataset=curr.fetchall() savedset=set() if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}): fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r') fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r') for line in fr_inbox.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) for line in fr_sent.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) fr_inbox.close() fr_sent.close() msglist=[] fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+') fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+') #print 'len(dataset)=',len(dataset) for (starttime,outgoing,freetext,remoteuid) in dataset: #print repr(outgoing),repr(freetext),repr(starttime) msgdict={ 'msg':freetext.encode('utf-8'), 'msgid':'%d-%s-%d'%(starttime, remoteuid.encode('utf-8'),len(freetext)), 'ts':starttime, } if msgdict['msgid'] in savedset: continue if outgoing==1: msgdict['tfrom']=LOCAL_PHONENUMBER msgdict['tto']=remoteuid.encode('utf-8') fw_sent.write(json.write(msgdict)+'\n') elif outgoing==0: msgdict['tto']=LOCAL_PHONENUMBER msgdict['tfrom']=remoteuid.encode('utf-8') fw_inbox.write(json.write(msgdict)+'\n') else: raise ValueError('Unknow outgoing=%d'%outgoing) #print msgdict # do it fw_inbox.close() fw_sent.close() curr.close() conn.close() return
Example #7
Source File: deathbycaptcha.py From bazarr with GNU General Public License v3.0 | 4 votes |
def _call(self, cmd, data=None): if data is None: data = {} data['cmd'] = cmd data['version'] = API_VERSION request = bytearray(json_encode(data), encoding='utf-8') response = None for _ in range(2): if not self.socket and cmd != 'login': self._call('login', self.userpwd.copy()) self.socket_lock.acquire() try: sock = self.connect() response = self._sendrecv(sock, request) except IOError as err: sys.stderr.write(str(err) + "\n") self.close() except socket.error as err: sys.stderr.write(str(err) + "\n") self.close() raise IOError('Connection refused') else: break finally: self.socket_lock.release() if response is None: raise IOError('Connection lost or timed out during API request') try: if PY2: return json_decode(response.decode('utf-8')) else: return json_decode(response) except Exception: raise RuntimeError('Invalid API response') if not response.get('error'): return response error = response['error'] if error in ('not-logged-in', 'invalid-credentials'): raise AccessDeniedException('Access denied, check your credentials') elif 'banned' == error: raise AccessDeniedException('Access denied, account is suspended') elif 'insufficient-funds' == error: raise AccessDeniedException( 'CAPTCHA was rejected due to low balance') elif 'invalid-captcha' == error: raise ValueError('CAPTCHA is not a valid image') elif 'service-overload' == error: raise OverflowError( 'CAPTCHA was rejected due to service overload, try again later') else: self.socket_lock.acquire() self.close() self.socket_lock.release() raise RuntimeError('API server error occured: %s' % error)