喜欢编程,热爱分享,希望能结交更多志同道合的朋友,一起在学习Python的道路上走得更远!
起源
需求是将前端传递的字符串转化为字典,后端(Python)使用这个字典当做参数体去请求任意接口。
采用的方法是使用json包中的loads函数, 示例如下:
import jsonif __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 -----------> test_json -----------> {'status': 'ok'}Process finished with exit code 0
可以看到输出是没什么大毛病的,但是作为一个严谨的人,思考了一下业务应用场景后,决定再测试一下是否能将字符串中的整数、浮点数、嵌套字典、数组、布尔值、空值成功转化。
![bf72b4ce3ab58ac7dfd5609acf28060f.png](https://img-blog.csdnimg.cn/img_convert/bf72b4ce3ab58ac7dfd5609acf28060f.png)
至于元组和日期类型就放过他吧 : )
探索的过程
探索代码:
import jsonif __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)
控制台输出:
type -----------> test_json -----------> {'status': {'number': 123, 'float': 123.321, 'list': [1, 2, 3, '1']}} Process finished with exit code 0
嗯,到目前为止都没啥毛病。
然而
![e3d5391922a790b3476139e079a9c4ce.png](https://img-blog.csdnimg.cn/img_convert/e3d5391922a790b3476139e079a9c4ce.png)
震惊!惊人发现
核心代码:
import jsonif __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 -----------> test_json -----------> {'status1': True, 'status2': False, 'status3': None}Process finished with exit code 0
相信聪明的读者已经发现,json.loads 函数可以 将字符串中的true,false, null成功转化为True,False,None。
![c41493dfe842c17ed9f8fb0d76343cb0.png](https://img-blog.csdnimg.cn/img_convert/c41493dfe842c17ed9f8fb0d76343cb0.png)
笔者查找 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
这,这代码,真硬气。
![4c3dfce8dc4faef081d1dfa366ce32bf.png](https://img-blog.csdnimg.cn/img_convert/4c3dfce8dc4faef081d1dfa366ce32bf.png)
往下翻还有惊喜哦:
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
![558e409835e802ea860dde1014833ae0.png](https://img-blog.csdnimg.cn/img_convert/558e409835e802ea860dde1014833ae0.png)
总结
每段代码背后都有小秘密,仔细挖掘就会得到不一样的乐趣与收获。
觉得文章还可以的话不妨收藏起来慢慢看,有任何意见或者看法欢迎大家评论!