json的四大函数介绍
在我们进行后端开发和爬虫开发的时候,常会遇到json
数据和python
数据的转换
, 而这些转换虽然简单,但是却很容易让人产生混淆和困惑, 接下来我将对json数据和python数据格式的转换做一个小的介绍,希望对各位读者能够起到一定的帮助…
- 1.loads : json字符串 --> python数据
import json
# json字符串需要使用双引号,且字符串中的字典数据最有一位不能使用逗号','
# 1.loads json字符串 --> python数据
json_string = """
{
"a":"hello",
"b":"hi"
}
"""
result = json.loads(json_string)
print(result, type(result))
- 结果
{'a': 'hello', 'b': 'hi'} <class 'dict'>
- 2.dumps : python数据 --> json字符串
import json
# 2.dumps python数据 --> json字符串
data = {
"a": "hello",
"b": "hi",
}
result = json.dumps(data)
print(result, type(result))
- 结果
{"a": "hello", "b": "hi"} <class 'str'>
- 3.load : json文件 --> python数据
import json
# 3.load json文件 --> python数据
with open('json.json', 'r', encoding='utf-8') as f:
# 第一种方式loads
# json_string = f.read()
# result = json.loads(json_string)
# print(result, type(result))
# 第二种方式 load
result = json.load(f)
print(result, type(result))
- json文件
- 结果
{'a': 'hello', 'b': 'hi', 'c': '中国'} <class 'dict'>
- 4.dump : python数据 --> json文件
import json
# 4.dump python数据 --> json文件
data = {
"a": "hello",
"b": "hi",
"c": "中国"
}
with open('data_out.json' , 'w', encoding='utf-8') as f:
# 第一种方式dumps
# json_string = json.dumps(data)
# f.write(json_string)
# 第二种方式dump
# ensure_ascii = False 设置输出的json文件的中文可以显示(可选参数)
# indent设置缩进空格的数量(使输出的json文件格式化, 可选参数)
json.dump(data, f, ensure_ascii=False, indent=2)
- 结果