Python JSON 模块:编码和解码 JSON 数据
Python 的 json 模块提供了一种简单的方式来编码和解码 JSON 数据。其中两个主要的函数是 json.dumps() 和 json.loads()。\n\n1. json.dumps 将一个 Python 数据结构转换为 str 类型:\n\npython\ndata = {\n 'name': 'haha',\n 'age': 20,\n}\njson_str = json.dumps(data)\nprint(json_str)\nprint(type(json_str))\nprint(type(data))\n\n\n输出结果:\n\n\n{"name": "haha", "age": 20}\n<class 'str'>\n<class 'dict'>\n\n\n2. json.loads 将一个 JSON 编码的字符串类型转换回一个 Python 数据结构:\n\npython\ndata2 = json.loads(json_str)\nprint(data2)\nprint(type(data2))\n\n\n输出结果:\n\n\n{'name': 'haha', 'age': 20}\n<class 'dict'>\n\n\n3. json.dump() 和 json.load() 用来编码和解码 JSON 数据,用于处理文件:\n\npython\nwith open('test.json', 'w') as f:\n json.dump(data, f)\n\nwith open('test.json', 'r') as f:\n data = json.load(f)\n
原文地址: https://www.cveoy.top/t/topic/pQJA 著作权归作者所有。请勿转载和采集!