python中JSON的常用操作

json在开发中的经常用到, 今天研究了一下, 在python中如何方便的使用json。

常用的操作, 无非就是dict转str,str转dict,dict存储到文件中,文件中导入成dict。

dict = json.loads(str)

str转dict

  • dict = json.loads(str)
import json
str1 = '{"name": "hjl", "age":"18"}'
print(str1, type(str1))
dict1 = json.loads(str1)
print(dict1, type(dict1))
{"name": "hjl", "age":"18"} <class 'str'>
{'age': '18', 'name': 'hjl'} <class 'dict'>

需要注意的是, str1在创建的时候, 会有很多的单引号和双引号,在这里, 字典的属性值需要使用双引号引用, 因此, 字符串最外层需要采用单引号引用。

dict转str

  • str = json.dumps(dict)
dict1 = {"name": "hjl", "age":"18"}
print(dict1, type(dict1))
str1 = json.dumps(dict1)
print(str1, type(str1))
{'age': '18', 'name': 'hjl'} <class 'dict'>
{"age": "18", "name": "hjl"} <class 'str'>

写入文件

  • json.dump()

写入str

str1 = '{"name": "hjl", "age":"18"}'   
with open('test.json','w',encoding='utf-8') as f:  
    json.dump(str1,f)  
    #f.close() 

自动生成test.json文件, 并在里面写入:

 "{\"name\": \"hjl\", \"age\":\"18\"}"

写入dict

str1 = '{"name": "hjl", "age":"18"}' 
dict1 = {"name": "xiaoming", "age":"19"}

with open('test.json','w',encoding='utf-8') as f:  
    json.dump(dict1,f)   
    #f.close() 

自动生成test.json文件, 并在里面写入:

 {"age": "19", "name": "xiaoming"}

读取文件

读取str, json文件里面存放的是str

with open('test.json','r',encoding='utf-8') as f:  
    dict1 = json.load(f)
    print(dict1, type(dict1)) 
{"name": "hjl", "age":"18"} <class 'str'>

读取dict, json文件里面存放的是dict

with open('test.json','r',encoding='utf-8') as f:  
    dict1 = json.load(f)
    print(dict1, type(dict1)) 
{'age': '19', 'name': 'xiaoming'} <class 'dict'>

猜你喜欢

转载自blog.csdn.net/u012678352/article/details/80805360