python json相关小随笔
json数据解析成字符串
json.dumps序列化时候对中文默认使用的ascii编码,想要输出真正的中文需要指定ensure_ascii=False
data="{\"dataType\": \"text\",\"field\": \"出生日期\"}"
json_data = json.dumps(data,ensure_ascii=False)
print(json_data)
#未添加ensure_ascii=False輸出結果 "{\"dataType\": \"text\",\"field\": \"\u51fa\u751f\u65e5\u671f\"}"
#添加ensure_ascii=False後輸出結果 {\"dataType\": \"text\",\"field\": \"出生日期\"}"
python连接数据库(mysql)
def savesomething(url,username,password,schema):
import os
#本地是
#import MySQLdb
#线上是
import pymysql
# 连接数据库 url username用户名 password:密码 schema:数据库名
db = pymysql.connect(url,username, password, schema, charset='utf8' )
cursor = db.cursor()
try:
cursor.execute("sql") # 运行sql
db.commit()
except:
db.rollback() # 出现异常回滚
db.close() #关闭连接
json文件读写
def json_dump(file_path, obj):
print('json_dump params: ', file_path, obj)
# with open(file_path, 'w') as f:
# json.dump(obj, f)
# f.close()
# 支持中文解析
import io
with io.open(file_path, 'w',encoding='utf-8') as f:
# json.dump(obj, f)
f.write(unicode(json.dumps(obj, ensure_ascii=False)))
def json_load(file_path):
print('json_load params: ', file_path)
# f = open(file_path, 'r', encoding='utf-8')
# jsonObj= json.load(f)
# print(jsonObj)
# f.close()
# return jsonObj
# 支持中文解析
import io
jsonObj = None
with io.open(file_path, 'r', encoding='utf-8') as f:
jsonObj= json.load(f, encoding='utf-8')
print(jsonObj)
return jsonObj
python中for循环
(第一次见到这种写法觉得厉害再此处记录)
list11=["a","b","c"]
outputs = [
x
for x in list11 if x=="a"# 此处可以直接添加条件
]
print(outputs )
#打印结果['a']
python 判断非空的几种方式
if where is None or where==’’:
if not add_mode_value.strip():
if where.strip() != “”: