• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python simplejson.dumps函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中simplejson.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_tuple_array_dump

 def test_tuple_array_dump(self):
     t = (1, 2, 3)
     expect = json.dumps(list(t))
     # Default is True
     sio = StringIO()
     json.dump(t, sio)
     self.assertEqual(expect, sio.getvalue())
     sio = StringIO()
     json.dump(t, sio, tuple_as_array=True)
     self.assertEqual(expect, sio.getvalue())
     self.assertRaises(TypeError, json.dump, t, StringIO(),
                       tuple_as_array=False)
     # Ensure that the "default" does not get called
     sio = StringIO()
     json.dump(t, sio, default=repr)
     self.assertEqual(expect, sio.getvalue())
     sio = StringIO()
     json.dump(t, sio, tuple_as_array=True, default=repr)
     self.assertEqual(expect, sio.getvalue())
     # Ensure that the "default" gets called
     sio = StringIO()
     json.dump(t, sio, tuple_as_array=False, default=repr)
     self.assertEqual(
         json.dumps(repr(t)),
         sio.getvalue())
开发者ID:All4Gis,项目名称:instagram2qgis,代码行数:25,代码来源:test_tuple.py


示例2: query_class

def query_class(className):
	connection = sqlite.connect(DATABASE_NAME)
	cursor = connection.cursor()
		
	classToken = re.match('(?P<department>[a-zA-Z]+)(?P<number>\d+)', className)

	classDept = classToken.group('department').upper()
	classNumber = classToken.group('number')

	cursor.execute("SELECT * FROM %s WHERE subject=\"%s\" AND number=%s" % (COURSE_TABLE_NAME, classDept, classNumber))
	res = cursor.fetchall()

	if len(res) <= 0:
		return json.dumps({'error': 'class not found'})

	# For each <class> find the corresponding sections and place in section table
	sectionTable = {}

	for row in res:
		rowPk = int(row[0])
		cursor.execute("SELECT * FROM %s WHERE course_pk=%d" % (SECTION_TABLE_NAME, rowPk))
		sectionResult = cursor.fetchall()
		
		for section in sectionResult:
			timeStart = to_military(section[5])
			timeEnd = to_military(section[6])
			
			try:
				sectionTable[section[3]].append(timeStart)
			except KeyError:
				sectionTable[section[3]] = [timeStart]
				
	return json.dumps(sectionTable)
			
开发者ID:smiley325,项目名称:uiucinfometrics,代码行数:33,代码来源:uiuc-catalog-ajax.py


示例3: api

 def api(self, command, **args):
     try:
         if command == 'difficulty':
             diff_q = query_single('SELECT curr_diff FROM stats')
             difficulty = {'difficulty': diff_q[0]}
             return json.dumps(difficulty)
         elif command == 'totalmint':
             total_m = query_single('SELECT total_mint FROM stats')
             minted = {'total minted': total_m[0]}
             return json.dumps(minted)
         elif command == 'getsigs':
             if args.get('adm', 'False') == 'False':
                 signatures = query_multi(
                     "SELECT s.signerId, s.signature,a.alias FROM signatures s "
                     "LEFT JOIN cvnalias a on s.signerId = a.nodeId "
                     "where s.height = %s",
                     args.get('block', '-1'))
             else:
                 signatures = query_multi(
                     "SELECT s.adminId, s.signature, a.alias FROM adminSignatures s "
                     "LEFT JOIN cvnalias a on s.adminId = a.nodeId "
                     "where height = %s",
                     args.get('block', '-1'))
             data = []
             if signatures:
                 for row in signatures:
                     data.append({'signer': row[0], 'sig': row[1], 'alias': row[2]})
             else:
                 data.append({'signer': 'no data', 'sig': 'available'})
             return json.dumps(data)
         return json.dumps({'error':'invalid'})
     except Exception:
         raise cherrypy.HTTPError(503)
开发者ID:FairCoinTeam,项目名称:faircoin2-cce-4.0,代码行数:33,代码来源:websrv.py


示例4: main

def main():
    prog, args = sys.argv[0], sys.argv[1:]
    if not args:
        print 'usage: %s username' % prog
        return
    tags = taglist(args[0])
    print simplejson.dumps(tags)
开发者ID:inky,项目名称:tumblr,代码行数:7,代码来源:taglist.py


示例5: text_to_transcript

def text_to_transcript(text_file, output_file):
    text = open(text_file).read()

    filedir = os.path.dirname(os.path.realpath(__file__))
    schema_path = os.path.join(
        filedir, "alignment-schemas/transcript_schema.json")

    transcript_schema = json.load(open(schema_path))

    paragraphs = text.split("\n\n")
    out = []
    for para in paragraphs:
        para = para.replace("\n", " ")
        if para == "" or para.startswith("#"):
            continue

        line = {
            "speaker": "narrator",
            "line": para
        }
        out.append(line)

    jsonschema.validate(out, transcript_schema)
    if output_file is None:
        print json.dumps(out, indent=4)
    else:
        with open(output_file, 'w') as f:
            f.write(json.dumps(out, indent=4))
    return
开发者ID:cjrd,项目名称:p2fa-vislab,代码行数:29,代码来源:text_to_transcript.py


示例6: get

    def get(self):
        created_by = self.get_current_user().strip('"')
        dealer = self.get_argument("dealer")
        numqrs = self.get_argument("numqrs")

        try:
            numqrs = int(numqrs)
        except ValueError:
            # front-end size interpret this as error
            self.write(simplejson.dumps([1]))
            self.set_header("Content-Type", "application/json")
            self.finish()
        try:
            connection = yield momoko.Op(self.db.getconn)
            with self.db.manage(connection):
                yield momoko.Op(connection.execute, "BEGIN")
                for _ in range(numqrs):
                    _uuid = qrgen.generate()
                    cursor = yield momoko.Op(self.db.execute,
                                             "INSERT INTO uuid_store (qr_uuid, user_id, \
                                              created_by, created_on) values (%s, %s, %s,\
                                              NOW())", (_uuid, dealer, created_by))
                yield momoko.Op(connection.execute, "COMMIT")
        except Except as e:
            if connection:
                yield momoko.Op(connection.execute, "ROLLBACK")
            mylogger.error(e)
            self.render("error.html", **{})
        else:
            # pack all images up and send them by mail
            self.write(simplejson.dumps([0]))
            self.set_header("Content-Type", "application/json")
开发者ID:acrispin,项目名称:dkads_dev,代码行数:32,代码来源:staff.py


示例7: test_encode_truefalse

 def test_encode_truefalse(self):
     self.assertEquals(json.dumps(
              {True: False, False: True}, sort_keys=True),
              '{"false": true, "true": false}')
     self.assertEquals(json.dumps(
             {2: 3.0, 4.0: 5L, False: 1, 6L: True, "7": 0}, sort_keys=True),
             '{"false": 1, "2": 3.0, "4.0": 5, "6": true, "7": 0}')
开发者ID:0xBF,项目名称:pygments.rb,代码行数:7,代码来源:test_dump.py


示例8: search

def search(request):
	img = []
	name = []
	price = []
	fatherid = []
	dict = {}
	if request.method == 'POST':
		req = simplejson.loads(request.raw_post_data)
		searchname = req['search']
		res = dish.objects.filter(name__contains = searchname)
		for i in res:
			img.append(i.img)
			name.append(i.name)
			price.append(i.price)
			fatherid.append(i.fatherid.id)
		dict['img'] = img
		dict['name'] = name
		dict['price'] = price
		dict['fatherid'] = fatherid
		dict['status'] = 'y'
		x  = simplejson.dumps(dict)
		return HttpResponse(x)
	dict['status'] = 'n'
	x = simplejson.dumps(dict)
	return HttpResponse(x)
开发者ID:YBJAY00000,项目名称:nenuwaiter,代码行数:25,代码来源:views.py


示例9: send_command

    def send_command(self, command, arguments = None):
        if command not in self.cmd_list and command != 'command-list':
            raise SuricataCommandException("No such command: %s", command)

        cmdmsg = {}
        cmdmsg['command'] = command
        if (arguments != None):
            cmdmsg['arguments'] = arguments
        if self.verbose:
            print("SND: " + json.dumps(cmdmsg))
        cmdmsg_str = json.dumps(cmdmsg) + "\n"
        if sys.version < '3':
            self.socket.send(cmdmsg_str)
        else:
            self.socket.send(bytes(cmdmsg_str, 'iso-8859-1'))

        ready = select.select([self.socket], [], [], 600)
        if ready[0]:
            cmdret = self.json_recv()
        else:
            cmdret = None

        if cmdret == None:
            raise SuricataReturnException("Unable to get message from server")

        if self.verbose:
            print("RCV: "+ json.dumps(cmdret))

        return cmdret
开发者ID:micsoftvn,项目名称:suricata,代码行数:29,代码来源:suricatasc.py


示例10: onedish

def onedish(request):
	dict = {}
	commentitem = []
	if request.method == 'POST':
		req = simplejson.loads(request.raw_post_data)
		fatherid = req['fatherid']
		dishname = req['dishname']
		onedish = dish.objects.filter(fatherid = fatherid,name = dishname)
		res = restaurant.objects.filter(id = fatherid)
		onedish_introduce = onedish[0].introduce
		onedish_price = onedish[0].price
		onedish_father = res[0].name
		onedish_img = onedish[0].img
		onedish_id = onedish[0].id
		onedish_mark = onedish[0].mark
		onedish_marknum = onedish[0].marknum

		commentlist = comment.objects.filter(dishid = onedish_id)
		for i in commentlist:
			commentitem.append(i.content)
		dict['commentlist'] = commentitem
		dict['onedish_id'] = onedish_id
		dict['onedish_marknum'] = onedish_marknum
		dict['onedish_mark'] = onedish_mark
		dict['onedish_introduce'] = onedish_introduce
		dict['onedish_price'] = onedish_price
		dict['onedish_img'] = onedish_img
		dict['onedish_father'] = onedish_father
		dict['status'] = 'y'
		x = simplejson.dumps(dict)
		return HttpResponse(x)
	dict['status'] = 'n'
	x = simplejson.dumps(dict)
	return HttpResponse(x)
开发者ID:YBJAY00000,项目名称:nenuwaiter,代码行数:34,代码来源:views.py


示例11: sendmessage

def sendmessage(request):
	dict = {}
	if request.method == 'POST':
		req = simplejson.loads(request.raw_post_data)
		message = req['message']
		phonenumber = req['phonenumber']
		sendCount = req['sendCount']
		sendSum = req['sendSum']
		sendCoupon = req['sendCoupon']
		sendUserId = req['sendUserId']
		dict['message'] = message
		dict['phonenumber'] = phonenumber
		dict['sendCoupon'] = sendCoupon
		dict['sendCount'] = sendCount
		dict['sendSum'] = sendSum
		dict['sendUserId'] = sendUserId
		userObject = user.objects.get(id = sendUserId)
		p = order(count= sendCount,number = sendSum,fatherid = userObject)
		p.save()
		if sendCoupon > 0:
			coupon.objects.get(id = sendCoupon).delete()
		# resp = requests.post(("https://sms-api.luosimao.com/v1/send.json"),auth=("api", "6bac001348b3495d558a8edffe0312bb"),data={"mobile": phonenumber,"message": message},timeout=3 , verify=False);
		# result = json.loads(resp.content)
		# dict['status'] = result['error']
		# x = simplejson.dumps(dict)
#不发送
		dict['status'] = "0"
		x = simplejson.dumps(dict)
		return HttpResponse(x)
	dict['status'] = '104'
	x = simplejson.dumps(dict)
	return HttpResponse(x)
开发者ID:YBJAY00000,项目名称:nenuwaiter,代码行数:32,代码来源:views.py


示例12: login

def login(request):
	dict= {}
	if request.method == 'POST':
		req = simplejson.loads(request.raw_post_data)
		rusername = req['username']
		rpassword = req['password']
		b = user.objects.filter(username=rusername)
		if(len(b) == 0):
			dict["status"] = '101'#用户名不存在返回101
		elif(b[0].password != rpassword):
			dict["status"] = '102'#密码错误返回102
		else:
			dict["status"] = 'yes'#验证成功返回yes
			dict['name']  = b[0].name
			dict['phonenumber'] = b[0].phonenumber
			dict['address'] = b[0].address
			dict['id'] = b[0].id

		x = simplejson.dumps(dict)
		return HttpResponse(x)

	else:
		dict['status'] = 'wa'
		x = simplejson.dumps(dict)
		return HttpResponse(x)
开发者ID:YBJAY00000,项目名称:nenuwaiter,代码行数:25,代码来源:views.py


示例13: retag_question

def retag_question(request, id):
    """retag question view
    """
    question = get_object_or_404(models.Post, id=id)

    try:
        request.user.assert_can_retag_question(question)
        if request.method == 'POST':
            form = forms.RetagQuestionForm(question, request.POST)

            if form.is_valid():
                if form.has_changed():
                    text = question.get_text_content(tags=form.cleaned_data['tags'])
                    if akismet_check_spam(text, request):
                        message = _('Spam was detected on your post, sorry if it was a mistake')
                        raise exceptions.PermissionDenied(message)

                    request.user.retag_question(question=question, tags=form.cleaned_data['tags'])
                if request.is_ajax():
                    response_data = {
                        'success': True,
                        'new_tags': question.thread.tagnames
                    }

                    if request.user.message_set.count() > 0:
                        #todo: here we will possibly junk messages
                        message = request.user.get_and_delete_messages()[-1]
                        response_data['message'] = message

                    data = simplejson.dumps(response_data)
                    return HttpResponse(data, content_type="application/json")
                else:
                    return HttpResponseRedirect(question.get_absolute_url())
            elif request.is_ajax():
                response_data = {
                    'message': format_errors(form.errors['tags']),
                    'success': False
                }
                data = simplejson.dumps(response_data)
                return HttpResponse(data, content_type="application/json")
        else:
            form = forms.RetagQuestionForm(question)

        data = {
            'active_tab': 'questions',
            'question': question,
            'form' : form,
        }
        return render(request, 'question_retag.html', data)
    except exceptions.PermissionDenied as e:
        if request.is_ajax():
            response_data = {
                'message': unicode(e),
                'success': False
            }
            data = simplejson.dumps(response_data)
            return HttpResponse(data, content_type="application/json")
        else:
            request.user.message_set.create(message = unicode(e))
            return HttpResponseRedirect(question.get_absolute_url())
开发者ID:ASKBOT,项目名称:askbot-devel,代码行数:60,代码来源:writers.py


示例14: bulk_index

    def bulk_index(self, index, docs, id_field="_id", parent_field="_parent"):
        chunks = []
        for doc in copy.deepcopy(docs):
            if "_type" not in doc:
                raise ValueError("document is missing _type field.")

            action = {"index": {"_index": index, "_type": doc.pop("_type")}}

            if doc.get(id_field) is not None:
                action["index"]["_id"] = doc[id_field]

            if doc.get(parent_field) is not None:
                action["index"]["_parent"] = doc.pop(parent_field)

            chunks.append(json.dumps(action))
            chunks.append(json.dumps(doc))

        payload = "\n".join(chunks) + "\n"
        url = self.build_url(index, None, "_bulk")
        asr = erequests.AsyncRequest("POST", url, self.session)
        asr.prepare(data=payload)

        r = self.map_one(asr)
        try:
            return r.json()
        except Exception as exc:
            raise ElasticSearchError(url) from exc
开发者ID:wilcox-tech,项目名称:elasticsearch-eventlet,代码行数:27,代码来源:elasticsearch_eventlet.py


示例15: broadcastNewPrograms

def broadcastNewPrograms(channel, programs, new_channel=False, to_owner=True, token=None):
  programs = programs if isinstance(programs, types.ListType) else [programs]

  response = {}
  response['type'] = 'new_programs'
  response['channel_id'] = channel.id
  response['channel'] = channel.toJson() if new_channel else None
  response['programs'] = [p.toJson(False) for p in programs]
  channels = memcache.get('web_channels') or {}
  
  if channel.privacy != constants.Privacy.PUBLIC and to_owner:
    if channel.user and channel.user.id in channels.iterkeys():
      webchannel.send_message(channels.get(channel.user.id), simplejson.dumps(response))
    elif token:
      webchannel.send_message(channels.get(token), simplejson.dumps(response))
  
  if channel.privacy == constants.Privacy.FRIENDS:
    if channel.user:
      for fid in channel.user.friends:
        if fid in channels.iterkeys():
          webchannel.send_message(channels.get(fid), simplejson.dumps(response))
  
  if channel.privacy == constants.Privacy.PUBLIC:
    for client in channels.iterkeys():
      webchannel.send_message(channels.get(client), simplejson.dumps(response))
开发者ID:ebby,项目名称:brokentv,代码行数:25,代码来源:broadcast.py


示例16: handle

    def handle(self, *args, **options):
        if len(args) != 0: raise CommandError("This command doesn't expect arguments!")
        flip_all = options['flip_all']
        code_red = options['code_red']

        es = get_es_new()
        es_indices = list(get_all_expected_es_indices())
        if code_red:
            if raw_input('\n'.join([
                'CODE RED!!!',
                'Really delete ALL the elastic indices and pillow checkpoints?',
                'The following indices will be affected:',
                '\n'.join([unicode(index_info) for index_info in es_indices]),
                'This is a PERMANENT action. (Type "code red" to continue):',
                '',
            ])).lower() == 'code red':
                for index_info in es_indices:
                    es.indices.delete(index_info.index)
                    print 'deleted elastic index: {}'.format(index_info.index)
            else:
                print 'Safety first!'
            return

        if flip_all:
            for index_info in es_indices:
                assume_alias(es, index_info.index, index_info.alias)
            print simplejson.dumps(es.indices.get_aliases(), indent=4)
开发者ID:saketkanth,项目名称:commcare-hq,代码行数:27,代码来源:ptop_es_manage.py


示例17: get_all_category

def get_all_category():
    category_name = request.args.get('category_name', '').replace('$', '&')

    if category_name:
      	query_field = mongo_util.generate_query(eval(request.args.get('field', '[]')))
        
        try:
            page = int(request.args.get('page', '1'))
        except:
            page = 1
        page = page if page > 0 else 1
        
        #get target collection from mongodb
        com_col = mongo_util.get_commodity_col()
        
        com_cursor = com_col.find(
            {'category': {'$elemMatch': {'$all': category_name.split('>')}}},
            query_field).skip((page - 1) * conf.ITEM_PER_PAGE).limit(conf.ITEM_PER_PAGE).batch_size(500)

        return json.dumps(map(lambda x:x, com_cursor), cls=ComplexEncoder)

    com_col = mongo_util.get_commodity_col()

    all_category = com_col.distinct('category.0')

    return json.dumps(map(lambda x: {'name': '>'.join(x)},
                      all_category), cls=ComplexEncoder)
开发者ID:donnyt1012,项目名称:Amazon_REST,代码行数:27,代码来源:amazon_rest.py


示例18: materias_view

def materias_view(request,pagina):
	if request.method == "POST":
		if "materia_id" in request.POST:
			try:
				id_mat = request.POST['materia_id']
				m = Materia.objects.get(pk=id_mat )
				mensaje = {"num_horas":"64","materia_id":m.id}
				m.delete() #Eliminar MAterias
				return HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')
			except:
				mensaje = {"num_horas":"120"}
				return HttpResponse(simplejson.dumps(mensaje),mimetype='application/json')
	


	lista_mat = Materia.objects.get_query_set() #Algo asi como select * from materias where horas=64
	paginator = Paginator(lista_mat,3) #Cuantos elementos quieres por pagina = 3
	try:
		page = int(pagina)
	except:
		page = 1
	try:
		listaMaterias = paginator.page(page)
	except (EmptyPage,InvalidPage):
		listaMaterias = paginator.page(paginator.num_pages)

	ctx = {'listaMaterias':listaMaterias}
	return render_to_response('materias/listaMaterias.html', ctx, context_instance=RequestContext(request))
开发者ID:YandryRamirez,项目名称:ESCOPROLnew,代码行数:28,代码来源:views.py


示例19: _getLastEntry

 def _getLastEntry(self, channel):
     """fetche the json data from either a file stored from the
     last request (only 1 request per 15 minutes allowed) or
     makes a new request and stores the result in a file as well
     """
     filename = plugins.makeChannelFilename('bitcoin', channel)
     # if file older than 15 minutes -> new query
     if os.path.exists(filename) == True:
         delta = datetime.timedelta(minutes=15)
         statbuf = os.stat(filename)
         now = datetime.datetime.now()
         modtime = datetime.datetime.fromtimestamp(statbuf.st_mtime) 
         if (now - delta) > modtime:
             data = self._fetchJsonData()
             self._writeToFile(simplejson.dumps(data), filename)
             log.info('new data')
             return simplejson.dumps(data)
         else:
             data = self._readFromFile(filename)
             log.info('old data')
             return  simplejson.dumps(data)
     else:
         data = self._fetchJsonData()
         self._writeToFile(simplejson.dumps(data), filename)     
         log.info('create new file and new data')
         return data
开发者ID:IT-Syndikat,项目名称:its-supybot-plugins,代码行数:26,代码来源:plugin.py


示例20: get_encoded_character

def get_encoded_character(deviceid,text):
    avd_device = "adb -s %s" % deviceid
    start_app = "%s shell am start -an com.symbio.input.unicode/.Main" % avd_device
    click_dpad_down = "%s shell input keyevent KEYCODE_DPAD_DOWN" % avd_device
    click_dpad_enter = "%s shell input keyevent KEYCODE_ENTER" % avd_device
    click_dpad_space = "%s shell input keyevent KEYCODE_SPACE" % avd_device
    # log("%r"%text)
    run_cmd(start_app)
    time.sleep(2)
    text_list = text.split()
    log(text_list)
    text_list = [x.encode('utf8') if is_pure_alnum(x) else x for x in text_list]
    log(text_list)
    for t in text_list[:-1]:
        cmd = "%s shell input text %r"  % (avd_device, json.dumps(t)[1:-1])
        cmd = wrapper(cmd)
        run_cmd(cmd)
        run_cmd(click_dpad_space)
    cmd = "%s shell input text %r"  % (avd_device, json.dumps(text_list[-1])[1:-1])
    cmd = wrapper(cmd)
    log(cmd)
    run_cmd(cmd)

    run_cmd(click_dpad_down)
    if __DEBUG__:
        run_cmd(click_dpad_down)
    run_cmd(click_dpad_enter)
开发者ID:nc1989,项目名称:monkey,代码行数:27,代码来源:inputunicode.py



注:本文中的simplejson.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python simplejson.get函数代码示例发布时间:2022-05-27
下一篇:
Python simplejson.dump函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap