本文整理汇总了Python中simplejson.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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())
示例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)
示例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)
示例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)
示例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
示例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")
示例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}')
示例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)
示例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
示例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)
示例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)
示例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)
示例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())
示例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
示例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))