欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

接受前端数据进行转换!

程序员文章站 2024-02-03 10:38:22
...

需求

1.接受前端传递的数据转化为字典,后端使用参数去请求任意接口。
解决办法:
json 中的 loads函数

For example

import json
class GoodsListView(View):
	def get(self, request):
	………
    demo_str = '{"status": "ok"}'
    demo_json = json.loads(demo_str)
    print('type --------> %s' % type(demo_json))
    print('demo_json --------> %s' % demo_json)

控制台输出:

type -----------> <class 'dict'>
demo_json -----------> {'status': 'ok'}

Process finished with exit code 0

loads这个函数当然没这么简单,它能将字符串中的整数、浮点数、嵌套字典、数组、布尔值、butes成功转化。

import json

if __name__ == '__main__':
    # 整数+浮点+嵌套字典+数组 测试
    demo_str = '{"status": {"number": 12322, "float": 12.21, "list": [1,2, "3"]}}'
    demo_json = json.loads(demo_str)
    print('type -----------> %s' % type(demo_json ))
    print('demo_json -----------> %s' % demo_json )

# if __name__ == '__main__':
    # 布尔值+空值 测试
    # demo_str = '{"status1": true, "status2": false, "status3": null}'
    # demo_json = json.loads(demo_str)
    # print('type -----------> %s' % type(demo_json ))
    # print('demo_json -----------> %s' % demo_json )

控制台输出;

type -----------> <class 'dict'>
demo_json-----------> {'status': {'number': 12322, 'float': 12.21, 'list': [1, 2,  '3']}}
 
Process finished with exit code 0
    
type -----------> <class 'dict'>
demo_json-----------> {'status1': True, 'status2': False, 'status3': None}

Process finished with exit code 0

就不多做赘叙了,给大家看看loads 的两段关键源码

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

Thank you for reading !!!

相关标签: json模块