Python处理JSON文件的四个常用函数详解
本文详细介绍Python中处理JSON数据的四个核心函数:json.load()用于从文件读取JSON,json.dump()用于将数据写入文件,json.loads()负责字符串转字典,json.dumps()实现字典转字符串。文章还包含一个单词查询系统的实战练习,帮助读者掌握JSON读写与类型转换的实际应用。
一、json.load()和json.dump()主要用于读写JSON数据
1. json.load()
从文件中读取JSON字符串
with open('data.json','r',encoding='utf-8') as f
print(json.load(f))2. json.dump()
将JSON字符串写入到文件中
content="{'name':'zhangsan','age':18}"
with open('text.json','w',encoding='utf-8') as f:
json.dump(content,f)二、json.loads()和json.dumps()主要用于字符串和字典之间的类型转换
3. json.loads()
将JSON字符串转换成字典类型
content="{'name':'zhangsan','age':18}"
json.loads(content)3. json.dumps()
将字典类型转换成JSON字符串
content={'name':'zhangsan','age':18}#假设这个是python定义的字典三、练习
编写单词查询系统:

1. 编写一个JSON格式的文件
{
"one": ["数字1"],
"two": ["数字2"],
"too": ["太","也","非常"]
}2. 编写Python方法
import json
from difflib import get_close_matches
data = json.load(open("data.json","r",encoding="utf-8"))
def translate(word):
word = word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys(),cutoff=0.5)) > 0:
yes_no = input("你要查询的是不是%s?,请输入yes或no:"%get_close_matches(word,data.keys(),cutoff=0.5))
yes_no = yes_no.lower()
if yes_no == "yes":
return data[get_close_matches(word,data.keys(),cutoff=0.5)[0]]
else:
return "你要查找的内容库里没有"
word = input("请输入你要查询的单词")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)到此这篇关于Python处理JSON文件的四个常用函数的文章就介绍到这了,更多相关Python处理JSON文件内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













