码迷,mamicode.com
首页 > Web开发 > 详细

json模块的使用

时间:2019-06-03 17:32:11      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:中文输入   不同   enc   pen   int   ensure   字典   new   user   

json数据类型其实就是字符串,他的样子就和字典一模一样,只是他的类型不同。我们需要把字典写入到文件中或者做接口测试时,我们都需要把字典转换成json格式或者把json格式转换成字典,所以我们就需要用到json模块。

使用json模块一样import json导入:

import json
 2 #解析json的
 3 
 4 # json_str = ‘‘‘
 5 # {"name":"xiaohei","age":18,"sex":"男","age":18}
 6 # ‘‘‘
 7 # res = json.loads(json_str) #把字符串(json串)转成字典
 8 # print(res)
 9 # print(type(json_str))
10 # print(type(res))
11 
12 dic = {
13     "xiaohei":{
14         "age":18,
15         "password":12345,
16         "sex":"男",
17         "addr":"北京"
18     },
19     "马春波":{
20         "age":18,
21         "password":12345,
22         "sex":"男",
23         "addr":"北京"
24     },
25     "王东泽":{
26         "age":18,
27         "password":12345,
28         "sex":"男",
29         "addr":"北京"
30     },
31 }
32 # res = json.dumps(dic,ensure_ascii=False,indent=4)#把字典变成字符串
33 # print(res)
34 # f = open(‘user.json‘,‘w‘,encoding=‘utf-8‘)
35 # f.write(res)
36 
37 #load 自己读
38 # f = open(‘user.json‘,encoding=‘utf-8‘)
39 # res = json.loads(f.read())
40 # print(res)
41 # res = json.load(f)
42 # print(res)
43 
44 #dump 自己写的
45 fw = open(‘newuser.json‘,‘w‘)
46 json.dump(dic,fw,indent=4,ensure_ascii=False)#indent表示缩进,一般4即可,ensure_ascii表示转码,false可以避免中文输入到文件中变成ascii码可读性差

  

json模块的使用

标签:中文输入   不同   enc   pen   int   ensure   字典   new   user   

原文地址:https://www.cnblogs.com/brainchan/p/10968650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!