1 __author__ = "JentZhang"
 2 
 3 import json
 4 
 5 user_info = {"id": 1000, "name": "zhangsan", "age": 25, "address": "xxxxxxxxxx", "mobile": "15966148787"}
 6 
 7 # 将字典转换为JSON字符串
 8 json_str = json.dumps(user_info)
 9 print(json_str)
10 print(type(json_str))
11 
12 # 将JSON字符串转换为字典
13 str_json = '{"name":"zhangsan","age":20}'
14 json_obj = json.loads(str_json)
15 print(json_obj)
16 print(type(json_obj))
17 
18 f = open('json_file','w')
19 dic = {'k1':'v1','k2':'v2','k3':'v3'}
20 json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
21 f.close()
22 
23 f = open('json_file')
24 dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
25 f.close()
26 print(type(dic2),dic2)

python3中json模块的用法

 

相关文章:

  • 2022-12-23
  • 2021-08-09
  • 2021-12-05
  • 2021-08-16
  • 2021-06-20
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
猜你喜欢
  • 2021-08-19
  • 2022-12-23
  • 2021-11-12
  • 2021-07-24
  • 2022-12-23
  • 2021-09-04
  • 2021-12-08
相关资源
相似解决方案