需求是将前端传递的字符串转化为字典,后端(Python)使用这个字典当作参数体去请求任意接口。前端
笔者采用的方法是使用json包中的loads函数, 示例以下:json
import json
if __name__ == '__main__':
test_str = '{"status": "ok"}'
test_json = json.loads(test_str)
print('type -----------> %s' % type(test_json))
print('test_json -----------> %s' % test_json)
复制代码
运行后控制台输出以下:后端
type -----------> <class 'dict'>
test_json -----------> {'status': 'ok'}
Process finished with exit code 0
复制代码
能够看到输出是没什么大毛病的,可是做为一个严谨的人,思考了一下业务应用场景后,决定再测试一下是否能将字符串中的整数、浮点数、嵌套字典、数组、布尔值、空值成功转化。数组
至于元组和日期类型就放过他吧 : )函数
探索代码:测试
import json
if __name__ == '__main__':
# 整数+浮点+嵌套字典+数组 测试
test_str = '{"status": {"number": 123, "float": 123.321, "list": [1,2,3, "1"]}}'
test_json = json.loads(test_str)
print('type -----------> %s' % type(test_json))
print('test_json -----------> %s' % test_json)
复制代码
控制台输出:spa
type -----------> <class 'dict'>
test_json -----------> {'status': {'number': 123, 'float': 123.321, 'list': [1, 2, 3, '1']}}
Process finished with exit code 0
复制代码
嗯,到目前为止都没啥毛病。3d
然而code
核心代码:cdn
import json
if __name__ == '__main__':
# 布尔值+空值 测试
test_str = '{"status1": true, "status2": false, "status3": null}'
test_json = json.loads(test_str)
print('type -----------> %s' % type(test_json))
print('test_json -----------> %s' % test_json)
复制代码
控制台输出:
type -----------> <class 'dict'>
test_json -----------> {'status1': True, 'status2': False, 'status3': None}
Process finished with exit code 0
复制代码
相信聪明的读者已经发现,json.loads 函数能够 将字符串中的true, false, null成功转化为True, False, None。
笔者查找 json.loads 函数源码 (Ctrl + B 已经按烂) 后,发现了这一段代码:
elif nextchar == 'n' and string[idx:idx + 4] == 'null':
return None, idx + 4
elif nextchar == 't' and string[idx:idx + 4] == 'true':
return True, idx + 4
elif nextchar == 'f' and string[idx:idx + 5] == 'false':
return False, idx + 5
复制代码
这,这代码,真硬气。
往下翻还有惊喜哦:
elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
return parse_constant('NaN'), idx + 3
elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
return parse_constant('Infinity'), idx + 8
elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
return parse_constant('-Infinity'), idx + 9
复制代码
每段代码背后都有小秘密,仔细挖掘就会获得不同的乐趣与收获。
正所谓 博客驱动开发,开发只是为了更好的 写做 !
欢迎你们扫码关注个人公众号「智能自动化测试」,回复:测试进阶教程,便可免费得到 进阶教程 ~
祝你们生活愉快,事事顺心~
--泰斯特
2019-5-24
复制代码