def save(self, fp): encoder = simplejson.JSONEncoder() self.dic["positive"] = self.positive self.dic["negative"] = self.negative self.dic["total"] = self.total line = encoder.encode(self.dic) + "\n" fp.write(line)
def test_encoding1(self): encoder = json.JSONEncoder(encoding='utf-8') u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' s = u.encode('utf-8') ju = encoder.encode(u) js = encoder.encode(s) self.assertEqual(ju, js)
def test_json_rpc_correct_response(self): """ Tests that the server responds as expected to a correctly formed JSON-RPC 2.0 request. Input: A correctly formed JSON-RPC 2.0 request containing an empty array of file names, an empty file name (direct input method) and a HTML fragment consisting of '<html></html>'. Expected Result: The returned JSON-RPC 2.0 response string should match the string expectedResponse, which contains the expected array of errors. """ conn = httplib.HTTPConnection("127.0.0.1:8080") fragment = base64.b64encode(b'<html></html>') params = [{"files": [], "document": fragment, "filename": ""}] request = json.JSONEncoder().encode({"jsonrpc": "2.0", "method": "parse_html", "params": params, "id": "A3s23"}) header = {"Content-type": "application/json"} conn.request("POST", "", request, header) response = conn.getresponse() conn.close() expectedResponse = '{"jsonrpc": "2.0", "result": [[1, 0, 5, {"name": "html"}], [25, 6, 12, {"name": "html"}]], "id": "A3s23"}' self.assertEqual(response.read(), expectedResponse, "Wrong response.")
def save_networks(self, filename, networks): f = open(filename, "w") f.write('{\n') macs = sorted(networks) enc = json.JSONEncoder() for mac in macs: network = self.networks[mac] f.write(' "%s": {\n' % mac) f.write(' "channel": %s, \n' % network["channel"]) f.write(' "cryptset": %s, \n' % network["cryptset"]) f.write(' "firsttime": %s, \n' % network["firsttime"]) f.write(' "lasttime": %s, \n' % network["lasttime"]) f.write(' "lat": %s, \n' % network["lat"]) f.write(' "lon": %s, \n' % network["lon"]) f.write(' "manuf": %s, \n' % enc.encode(network["manuf"])) if "signal_dbm" in network and "last" in network["signal_dbm"]: f.write(' "signal_dbm": {\n') f.write(' "last": %s, \n' % network["signal_dbm"]["last"]) f.write(' "max": %s, \n' % network["signal_dbm"]["max"]) f.write(' "min": %s\n' % network["signal_dbm"]["min"]) f.write(' }, \n') f.write(' "ssid": %s, \n' % enc.encode(network["ssid"])) f.write(' "type": "%s",\n' % network["type"]) f.write(' "comment": %s\n' % enc.encode(network["comment"])) if mac != macs[-1]: f.write(' }, \n') else: f.write(' }\n') f.write('}') f.close()
def delete(name, c, p): print "Trying to delete QoSPath %s" % name # circuitpusher --controller {IP:REST_PORT} --delete --name {CIRCUIT_NAME} try: print "Deleting circuit" cmd = "./circuitpusher.py --controller %s:%s --delete --name %s" % ( c, p, name) subprocess.Popen(cmd, shell=True).wait() except Exception as e: print "Error deleting circuit, Error: %s" % str(e) exit() qos_s = os.popen( "./qosmanager2.py --list --type policies --controller %s --port %s" % (c, p)).read() #pull only the right info from response qos_s = qos_s[qos_s.find("[", qos_s.find("[") + 1):qos_s.rfind("]") + 1] data = simplejson.loads(qos_s) sjson = simplejson.JSONEncoder(sort_keys=False, indent=3).encode(data) jsond = simplejson.JSONDecoder().decode(sjson) #find policies that start with "<pathname>." l = len(jsond) for i in range(l): n = jsond[i]['name'] if name in n: pol_id = jsond[i]['policyid'] try: cmd = "./qosmanager2.py --delete --type policy --json '{\"policy-id\":\"%s\"}' -c %s -p %s " % ( pol_id, c, p) print cmd subprocess.Popen(cmd, shell=True).wait() except Exception as e: print "Could not delete policy in path: %s" % str(e)
def cqlQuery(query): sys.stderr.write("QUERY: %s\n" % (query)) # prepare parameters method = 'view' attrs = dict(corpname='preloaded/bnc', q='q'+query, format='json') encoded_attrs = urllib.quote(simplejson.JSONEncoder().encode(attrs)) url = base_url + method + '?json=%s' % encoded_attrs # creating query string request = urllib2.Request(url) # authentication base64string = base64.encodestring('%s:%s' % (usr, passwd))[:-1] request.add_header("Authorization", "Basic %s" % base64string) # json data receiving file = urllib2.urlopen(request) data = file.read() file.close() return data;
def test_encoding1(): encoder = S.JSONEncoder(encoding='utf-8') u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' s = u.encode('utf-8') ju = encoder.encode(u) js = encoder.encode(s) assert ju == js
def __init__(self, file, **kwargs): super().__init__(file, **kwargs) self.encoder = json.JSONEncoder( ensure_ascii=True, default=json_converters, for_json=True, iterable_as_array=True, )
def print_activities(activity_list): events = activity_list['items'] print '\nRetrieved %d activities.' % len(events) for i in range(len(events)): print '\nEvent %d : %s' % (i, simplejson.JSONEncoder().encode( events[i])) print '\nNext URL : %s' % (activity_list['next']) print '======================================================================'
def readfile(file): output_file = open("logs.jsonl", "w") index = 1 #check necessary file size checking statinfo = os.stat(file) #just a guestimate. I believe a single entry contains atleast 150 chars if statinfo.st_size < 150: print "Not a valid access_log file. It does not have enough data" else: for line in fileinput.input(file): if line != "\n": #don't read newlines output_file.write(json.JSONEncoder().encode(actionString(index)) + "\n") output_file.write(json.JSONEncoder().encode(line2dict(line)) + "\n") index = index + 1 fileinput.close()
def mainf(): print("mainf") if args.demo: if args.verbose: k = 1 print(1) wifi_data = [('00-fe-f4-25-ee-30', -40), ('02-fe-f4-25-ee-30', -44), ('12-fe-f4-25-ee-30', -44), ('00-26-5a-7e-0d-02', -60), ('90-01-3b-30-04-29', -60), ('2c-b0-5d-bd-db-4a', -50)] else: print(2) wifi_scan_method = check_prerequisites() if args.verbose: k = 1 print(12) wifi_data = get_signal_strengths(wifi_scan_method) print(wifi_data) if args.verbose: k = 1 print(3) location_request = { 'considerIp': False, 'wifiAccessPoints': [{ "macAddress": mac, "signalStrength": signal } for mac, signal in wifi_data] } if args.api_key: print(4) API_KEY = args.api_key if not API_KEY or API_KEY is 'YOUR_KEY': k = 1 print(6) exit(1) else: location_request['considerIp'] = True json_data = simplejson.JSONEncoder().encode(location_request) location_request['considerIp'] = True http_request = urllib2.Request( 'https://www.googleapis.com/geolocation/v1/geolocate?key=' + API_KEY) http_request.add_header('Content-Type', 'application/json') if args.verbose: k = 1 api_result = simplejson.loads( urllib2.urlopen(http_request, json_data).read()) if args.verbose: k = 1 print(api_result) return (api_result['location']['lat'], api_result['location']['lng'], api_result['accuracy'])
def getall(): try: conn = pymysql.connect(**config) cursor = conn.cursor() cursor.execute( 'SELECT name, lastname, phone, email, age, CONCAT("Registrado el día: ", DATE(customers.registration_date)) AS registration_date, genders.gender, status.status, street, city, state, code, country, additional FROM customers LEFT JOIN genders USING(id_gender) LEFT JOIN status USING(id_status)' ) rows = cursor.fetchall() cursor.close() conn.close() res = json.JSONEncoder().encode({'status': 200, 'rows': rows}) return res except Exception as e: res = json.JSONEncoder().encode({'status': 400, 'error': format(e)}) return res
def gen_config_data_for_koan(self): """ Encode configuration data. Return json object for Koan. :return: A json string for koan. """ json_config_data = json.JSONEncoder(sort_keys=True, indent=4).encode( self.gen_config_data()) return json_config_data
def default(self, obj): """If input object is an ndarray it will be converted into a list """ if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, np.generic): return np.asscalar(obj) # Let the base class default method raise the TypeError return json.JSONEncoder(self, obj)
def render_portalUserInfo_mongo(self, username): try: customer_mongo = self.mongo_cache.read_portalChannels_mongo( username, isuser=True) return rediscache.refresh_user_channel_portal( username, sjson.JSONEncoder().encode(customer_mongo)) except Exception, e: logger.error( 'render portalUser Info_mongo of user= %s from mongo to redis exception: %s' % (username, traceback.format_exc(e)))
def test_encoding1(self): # This test is not appropriate for Python 3: You're not supposed # to pass bytes to JSON APIs. if not PY3: encoder = json.JSONEncoder(encoding='utf-8') uu = u( '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}') s = uu.encode('utf-8') ju = encoder.encode(uu) js = encoder.encode(s) self.assertEquals(ju, js)
def refresh_channels_portal(username, channels_arr): channels_map = {} for channel in channels_arr: channel_utf8 = sjson.JSONEncoder().encode(channel) channels_map.setdefault(channel.get('channelName'), channel_utf8) if channels_map: pipe = portal_cache.pipeline() pipe.delete(CHANNELS_PORTAL_PREFIX % username) pipe.hmset(CHANNELS_PORTAL_PREFIX % username, channels_map) pipe.execute() return channels_map
def get(self): encoder = simplejson.JSONEncoder() stuff = [] for update in SomeUpdate.gql('ORDER BY updated DESC').fetch(10): stuff.append({ 'time': str(update.updated), 'title': update.title, 'content': update.content, 'source': update.link }) self.response.out.write(encoder.encode(stuff))
def geocode(address, sensor="false", **geo_args): """ Returns a city name for an address/zipcode/search """ json = simplejson.JSONEncoder() geo_args.update({'address': address, 'sensor': sensor}) url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args) result = simplejson.load(urllib.urlopen(url)) return json.encode([s['formatted_address'] for s in result['results']])
def get_extra_fields_json(self): try: fields = open_gadget(self.gadget).gadget_info()['fields'] except: return [] newFields = [] for field in fields: value = read_value_from_xml_field(field['id'], self.modifier) if value != '': field['value'] = value newFields.append(field) return mark_safe(json.JSONEncoder().encode(newFields))
def json_handler(*args, **kwargs): """Custom json handle to convert RdiffDate to str.""" value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) def default(o): if hasattr(o, '__json__'): return o.__json__() raise TypeError(repr(o) + " is not JSON serializable") encode = json.JSONEncoder(default=default, ensure_ascii=False).iterencode for chunk in encode(value): yield chunk.encode('utf-8')
def approve_transfer(request): if request.method == 'POST': auth_error = authenticate_request(request) response = {} if auth_error == None: message = '' error = None directory = request.POST.get('directory', '') type = request.POST.get('type', 'standard') error = approve_transfer_via_mcp(directory, type, request.user.id) if error != None: response['message'] = error response['error'] = True else: response['message'] = 'Approval successful.' if error != None: return HttpResponseServerError( simplejson.JSONEncoder().encode(response), mimetype='application/json' ) else: return HttpResponse( simplejson.JSONEncoder().encode(response), mimetype='application/json' ) else: response['message'] = auth_error response['error'] = True return HttpResponseForbidden( simplejson.JSONEncoder().encode(response), mimetype='application/json' ) else: raise Http404
class JSON: """ JSON implementation used for packet en/decoding """ encoder = simplejson.JSONEncoder(ensure_ascii=False, separators=(',', ':')) decoder = simplejson.JSONDecoder() def encode(self, obj): """encode an object, returning a utf8 encoded string (not a unicode string!)""" return self.encoder.encode(obj).encode('utf-8') def decode(self, string): return self.decoder.decode(string)
def __init__(self, controller): """Takes one argument: the instance of the controller Class.""" pluginmanager.iterator.__init__(self) self.controller = controller self.encoder = json.JSONEncoder().encode self.decoder = json.JSONDecoder().decode self.pingAnswer = False self.pwhash = None self.nickname = "" self.connector = None self.reconnecting = False self.delimiter = '\n' self.isConnected = False
def _sendjson(self, host): data = {'id': 1, 'method': 'slim.request', 'params': ["", ["rescan"]]} data = simplejson.JSONEncoder().encode(data) content = {'Content-Type': 'application/json'} req = urllib2.Request(host + '/jsonrpc.js', data, content) try: handle = urllib2.urlopen(req) except Exception, e: logger.warn('Error opening LMS url: %s' % e) return
def get_data(self): data = {} data["hostname"] = self.hostname data["systemUptime"] = "" data["spaceAvailable"] = self.get_available_space() data["averageLoads"] = self.get_average_load() data["serviceUptime"] = self.get_service_uptime() data["loc"] = self.loc data["logs"] = {} data["kvstore"] = self.get_successors_data() data["index"] = self.node_circle.my_node.location return json.JSONEncoder().encode(data)
def do_post(): # conn = httplib.HTTPConnection("223.202.45.190") conn = httplib.HTTPConnection("r.chinacache.com") # conn = httplib.HTTPConnection("223.202.52.83") headers = {"Content-type": "application/json"} for i in range(15, 16): # params = ({"username": "******","password": "******","speed": "","startTime": "","validationType": "MD5","isOverride ": 1,"tasks": [{"id":"124","url": "http://rdbtest1.ccgslb.net/QtXml4.dll","md5": "c53df18d306639f9fd424f8046346144"}]}) # params = ({"username": "******","password": "******","speed": "","startTime": "","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://*.mtmos.com/index.html"}]}) # params = ({"username": "******","password": "******","speed": "","startTime": "","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://jiang.dawx.com/app100688853/sgonline022001/swf_new/tipsui.swf"}]}) # params = ({"username": "******","password": "******","speed": "","startTime": "","validationType": "BASIC","isOverride ": 1,"tasks": [{"id":"1393335719102","url": "http://jiang.dawx.com/app100688853-000/sgonline022001/swf_new/tipsui.swf"}]}) # params = ({'username': '******', 'tasks': [{'url': 'http://video.cztv.com/cztv/vod/2015/06/23/6bbc845aa3094e039417a11ee17b9769/h264_1500k_mp4.mp4', 'id': '116233'},{'url': 'http://video.cztv.com/cztv/vod/2015/06/23/6bbc845aa3094e039417a11ee17b9769/h264_800k_mp4.mp4', 'id': '116234'},{'id': '116235','url': 'http://video.cztv.com/cztv/vod/2015/06/23/6bbc845aa3094e039417a11ee17b9769/h264_450k_mp4.mp4'},{'url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_1500k_mp4.mp4', 'id': '70821'},{'url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_800k_mp4.mp4', 'id': '70822'},{'id': '70823','url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_450k_mp4.mp4'}], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': ''}) # params = ({'username': '******', 'tasks': [{'url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_1500k_mp4.mp4', 'id': '70821'},{'url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_800k_mp4.mp4', 'id': '70822'},{'id': '70823','url': 'http://video.cztv.com/cztv/vod/2015/06/20/1532ef44abd24cecb760d219b8be7486/h264_450k_mp4.mp4'}], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': ''}) # params = ({"username": "******","password": "******","speed": "1980.123k","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://mlftp.vxinyou.com/1.14.0/data0_1.16.0.epk"}]}) # params = ({'username': '******', 'parent':'rdbrd',"compressed": True,'tasks': [{'url': 'http://rdbtest2.ccgslb.net/1.txt', 'id': '1142733'}], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': ''}) # params = ({'username': '******', 'parent':'people','isSub':'True','tasks': [{'url': 'http://video02.cnlive.com/video/data1/2015/0921/74026/301/b179c7d831054f08b14da860fa5dfb3c_74026_30111.m3u8', 'id': '1142733'}], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': ''}) params = ({ 'username': '******', 'tasks': [{ 'url': 'http://uri.xdcdn.net/jsk/file/8d5b52c30ded5b82e7e506784189ce52d4388bc8/sharedassets0.assets.lz', 'id': '49543' }], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': '' }) # params = ({'username': '******', 'tasks': [{'url': 'http://v2.cztv.com/cztv/vod/2015/08/18/5EF106BB76064eaeA0B7B4E9F6B2C442/h264_1500k_mp4.mp4', 'id': '49543'},{'url': 'http://v2.cztv.com/cztv/vod/2015/08/03/373caa3e65cc431a83b91f0bd62caacf/h264_450k_mp4.mp4', 'id': '49544'},{'url': 'http://v2.cztv.com/cztv/vod/2015/08/03/101557950bb24e01bff169c932d15e1c/h264_1500k_mp4.mp4', 'id': '49545'},{'url': 'http://v2.cztv.com/cztv/vod/2015/08/03/101557950bb24e01bff169c932d15e1c/h264_800k_mp4.mp4', 'id': '49546'},{'url': 'http://v2.cztv.com/cztv/vod/2015/08/03/101557950bb24e01bff169c932d15e1c/h264_450k_mp4.mp4', 'id': '49547'},{'url': 'http://v2.cztv.com/cztv/vod/2015/07/29/5ad31b6dc3044a068798f415834e72cb/h264_1500k_mp4.mp4', 'id': '49548'},{'url': 'http://v2.cztv.com/cztv/vod/2015/07/29/5ad31b6dc3044a068798f415834e72cb/h264_800k_mp4.mp4', 'id': '49549'},{'url': 'http://v2.cztv.com/cztv/vod/2015/07/29/5ad31b6dc3044a068798f415834e72cb/h264_450k_mp4.mp4', 'id': '49550'}], 'nest_track_level': 0, 'startTime': '', 'validationType': 'BASIC', 'password': '******', 'speed': ''}) # params = ({"username": "******","password": "******","speed": "1980.123k","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://mlftp.vxinyou.com/1.14.0/data0_1.16.0.epk"}]}) # params = ({"username": "******","password": "******","speed": "1980.123k","startTime": "","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://apk.r1.market.hiapk.com/data/upload/apkpatch/2014/6_14/14/6b3a8c6b-d2c1-47f8-8e5a-d71994817836.patch"}]}) # params = ({"username": "******","password": "******","speed": "","startTime": "","validationType": "BASIC","isOverride ": 1,"tasks": [{"id": i,"url": "http://apk.r1.market.hiapk.com/data/upload/apkpatch/2014/6_14/14000/6b3a8c6b-d2c1-47f8-8e5a-d71994817836.patch"}]}) # params = ({"username": "******","password": "******","speed": "600.456k","startTime": "","validationType": "MD5","isOverride ": 1,"tasks": [{"id": i,"md5":"47e9e575b97df2078165cafb73f9cbbd","url": "http://apk.r1.market.hiapk.com/data/upload/apkpatch/2014/6_14/14/6b3a8c6b-d2c1-47f8-8e5a-d71994817836.patch"}]}) # params = ({"username": "******","password": "******","speed": "","startTime": "2014-07-07 17:18:00","validationType": "MD5","isOverride ": 1,"tasks": [{"id": i,"md5":"47e9e575b97df2078165cafb73f9cbbd","url": "http://apk.r1.market.hiapk.com/data/upload/apkpatch/2014/6_14/14/6b3a8c6b-d2c1-47f8-8e5a-d71994817836.patch"}]}) # conn.request("POST", "/content/preload", json.JSONEncoder().encode(params), headers) conn.request("POST", "/internal/preload", json.JSONEncoder().encode(params), headers) response = conn.getresponse() print response.read() #params_2 = urllib.urlencode({'558a46ea2b8a68be466c1ddcusername': '******', 'password': '******', 'task': '{"urls":["http://ww4.sinaimg.cn/bmiddle/61b69811gw1dld19fhhelj.jpg","http://ww4.sinaimg.cn/mw600/6f40d48agw1dpzmm9vtozj.jpg","http://ww4.sinaimg.cn/thumbnail/6dceb033jw1doxgrr5z7hj.jpg","http://ww4.sinaimg.cn/thumbnail/62d8a08bjw1dqwyqv2lg6j.jpg"]}'}) #params_2 = urllib.urlencode({'username': '******', 'password': '******', 'task': '{"dirs":["http://shengdafds.peixin.ccgslb.net/test/","http://gfxz.autopatch.sdo.com/test","http://launcher.autopatch.sdo.com/test"],"callback":{"url":"http://www.a.com/listener","email":["*****@*****.**","*****@*****.**"],"acptNotice":true}}'}) #f_2 = urllib.urlopen("http://223.202.45.190/content/refresh" , params_2) #f_2 = urllib.urlopen("http://192.168.158.15:8000/content/refresh" , params_2) conn.close()
def read_and_write_file(json_file_path, new_json_file_path): """Read in the json dataset file and write it out to a csv file, given the column names.""" rests = list() with open(json_file_path, "r") as old: for line in old: line_contents = json.loads(line) #print line_contents['categories'] if 'Restaurants' in line_contents['categories']: rests.append(line_contents) #print "True" json.JSONEncoder().encode(rests) with open(new_json_file_path, "w+") as newf: json.dump(rests, newf)
def unapproved_transfers(request): if request.method == 'GET': authorized = authenticate_request(request) if authorized == True: message = '' error = None unapproved = [] jobs = models.Job.objects.filter( (Q(jobtype="Approve transfer") | Q(jobtype="Approve DSpace transfer") | Q(jobtype="Approve bagit transfer")) & Q(currentstep='Awaiting decision')) for job in jobs: # remove standard transfer path from directory (and last character) type_and_directory = job.directory.replace( get_modified_standard_transfer_path() + '/', '', 1)[:-1] transfer_watch_directory = type_and_directory.split('/')[0] transfer_type = helpers.transfer_type_by_directory( transfer_watch_directory) job_directory = type_and_directory.replace( transfer_watch_directory + '/', '', 1) unapproved.append({ 'type': transfer_type, 'directory': job_directory }) # get list of unapproved transfers # return list as JSON response = {} response['results'] = unapproved if error != None: response['message'] = error response['error'] = True else: response[ 'message'] = 'Fetched unapproved transfers successfully.' return HttpResponse(simplejson.JSONEncoder().encode(response), mimetype='application/json') else: return HttpResponseForbidden() else: return Http404
def makePowerMessage(self, id, nclock, nVrmsAvg, nVrmsMax, nVrmsMin): packet = simplejson.JSONEncoder().encode( { PKConst.gateway_id : ThingConfig.gw_id, PKConst.switch_id : id, PKConst.cmd : PKConst.cmd_power, PKConst.time : nclock, PKConst.vrms_avg : nVrmsAvg, PKConst.vrms_max : nVrmsMax, PKConst.vrms_min : nVrmsMin } ) return packet