【python】json.dumps() 与 json.loads() 用法

一、JSON介绍

JSON代表JavaScript对象符号。它是一种轻量级的数据交换格式,用于存储和交换数据。它是一种独立于语言的格式,非常容易理解,因为它本质上是自描述的。 python中有一个内置包,它支持JSON数据,称为json。 JSON中的数据表示为quoted-strings,由大括号{}之间的键值映射组成。通俗来说就是一种在接口中易于使用的数据处理模块,但是json不属于数据格式。

二、Python和Json数据类型的映射

JSONPython
objectdict
arraylist
stringstr
numberint
trueTrue
falseFalse
nullNone

三、json.load(s)与json.dump(s)区别

json.load:表示读取文件,返回python对象
json.dump:表示写入文件,文件为json字符串格式,无返回
json.dumps:将python中的字典类型转换为字符串类型,返回json字符串 [dict→str]
json.loads:将json字符串转换为字典类型,返回python对象 [str→dict]
load和dump处理的主要是 文件
loads和dumps处理的是 字符串

在这里插入图片描述

json.load()从json文件中读取数据
json.loads()将str类型的数据转换为dict类型
json.dumps()将dict类型的数据转成str
json.dump()将数据以json的数据类型写入文件中
在这里插入图片描述

四、测试

4.1 json.dumps()

import json

data = {
    'fruit':'apple',
    'vegetable':'cabbage'
}
print(data,type(data))

data = json.dumps(data)  # dict转json
print(data,type(data))

返回:

{'fruit': 'apple', 'vegetable': 'cabbage'} <class 'dict'>
{"fruit": "apple", "vegetable": "cabbage"} <class 'str'>

4.2 json.loads()

data = """{
"fruit": "apple",
"vegetable": "cabbage"
}"""
# 一般此时data为request.text返回值
print(data, type(data))
data = json.loads(data)
print(data, type(data))

返回:

{
"fruit": "apple",
"vegetable": "cabbage"
} <class 'str'>
{'fruit': 'apple', 'vegetable': 'cabbage'} <class 'dict'>

4.3 json.dump()

1.写str
a.py中:

data = "wyt"
with open('b.json', 'w') as f:
    json.dump(data, f)

with open('b.json','r',encoding='utf-8') as f :
    f_str = json.load(f)
    print(f_str,type(f_str))

返回:

wyt <class 'str'>

2.写dict
a.py中:

data = {
    'fruit':'apple',
    'vegetable':'cabbage'
}
with open('b.json', 'w') as f:
    json.dump(data, f)

with open('b.json','r',encoding='utf-8') as f :
    f_str = json.load(f)
    print(f_str,type(f_str))

返回:

{'fruit': 'apple', 'vegetable': 'cabbage'} <class 'dict'>

4.4 json.load()

a.json中存在:

{
"fruit": "apple",
"vegetable": "cabbage"
}

a.py中:

with open('a.json','r',encoding='utf-8') as f :
    f_str = json.load(f)
    print(f_str,type(f_str))

返回:

{'fruit': 'apple', 'vegetable': 'cabbage'} <class 'dict'>

五、报错分析

5.1 本地代码

data = '''{
'fruit':'apple',
'vegetable':'cabbage'
}'''
data = json.loads(data)

5.2 报错返回

在这里插入图片描述

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)

5.3 报错分析与解决

json内部要使用双引号。

data = """{
"fruit": "apple",
"vegetable": "cabbage"
}"""
data = json.loads(data)
print(data, type(data))

返回:

{'fruit': 'apple', 'vegetable': 'cabbage'} <class 'dict'>

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年3月5日 下午10:55
下一篇 2023年3月5日 下午10:56

相关推荐