python实现字符串与二进制之间的转换

通过抓包返回的响应值(json格式数据)在平台转义:

http://www.bejson.com/

图片是我的示例json,先进行格式化,然后压缩→转义

将json转义后才能赋值给变量 

源代码:

def encode(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])


def decode(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])


var1 = encode(
    "{\"code\":\"000\",\"data\":{\"records\":[{\"itemID\":0,\"areaName\":\"一楼明档\",\"areaKey\":\"0001\",\"areaID\":0,\"tableCode\":\"0107\",\"tableName\":\"7号桌\",\"tableName2\":\"7号桌\",\"isTemporary\":0,\"isRoom\":0,\"defaultPerson\":2,\"tableStatus\":1,\"lockedBy\":\"\",\"bookOrderNo\":\"\",\"createBy\":\"999|999\",\"currPerson\":12,\"createTime\":\"20210715152026\",\"orderTotalAmount\":0,\"saasOrderKey\":\"0107002\",\"userInfo\":\"\",\"childTableIndex\":0}]},\"msg\":\"成功\",\"success\":\"true\",\"traceID\":\"\",\"clientType\":\"\"}")
print(var1)  # json 转 二进制

print(decode(var1))  # 二进制 转 json

python实现字符串与二进制之间的转换

 python实现字符串与二进制之间的转换

 

python实现字符串与二进制之间的转换

 

上一篇:Python全栈之路系列之深浅拷贝


下一篇:Java Web学习Day02 Response