json 的简单应用

今天做爬虫时的一点盲区 :字符串, 字典,写到同一个文件中。难以利用!
比如这样的数据:
str = “hi,budy. i like 52pojie!”
dirt = {“陈墨”:["男",“22”]}

一、保存到txt文件
      

[Python] 纯文本查看 复制代码
1
2
3
with open("text.txt","w") as f:        f.write(str)
        #write()只能保存string
        f.write(str(dirt))


这样读出来,怎么读都是字符串。dirt难以利用。

二、保存到json数据,json.load 和 json.dump的使用
     

[Python] 纯文本查看 复制代码
1
2
with open( "a.json", "w") as f:         json.dump(str,f)
        json.dump(dirt,f)


     读取时使用json。dump(),这样会产生错误,一个是字符串,一个是字典。一起读数据数据类型不统一。
    那就分开读,也就是第三种方式:
三、,json.load 和 json.dump+json.loads()的使用
     

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import json
 
 
def  read_json():
      with open("a.json", "r") as f:
          #每一行为一个列表的元素,各行独立
          data = f.readlines()
          for  dat in data:
              #去掉行后的空白,换行或者回车
              dat = dat.rstrip()
              #利用json.loads()恢复每一行的保存前数据类型,
              dir = json.loads(dat)
              #打印数据类型
              print(type(dir))
              print(dir)
 
def write_json():
     with open( "a.json", "w") as f:
         str = [1,2,5,3,4,5]
         json.dump(str,f)
         #每行后换行,保证每条数据相互独立。
         f.write("\n")
         str  ={11:22,33:44}
         json.dump(str,f)
         f.write("\n")
         str = "hello budy!"
         json.dump(str,f)
     #这样会产生比较多的空间浪费。每行有可能不到一半,
 
if  __name__ == "__main__":
    write_json()
    read_json()




这样做,以我目前的水平来说,方便了很多,保存的数据很方便就可以按照他原来的数据类型去使用。但是产生的空间浪费也很多,
比如一行100个字节,可能就用了10个字节

posted @ 2019-08-06 09:00  不夜男人  阅读(259)  评论(0编辑  收藏  举报