python的json模块中dumps和loads、dump和load以及报错JSONDecode:Expecting property name enclosed in double quotes:

python的json模块中dumps和loads、dump和load

import json
data = {1:'a', 2:'b', 3:'c'}		# 数据

1. dumps和loads

注意: dumps和loads不仅仅对字典起作用

  • dumps(), 将python对象转换为josn字符串

    res1 = json.dumps(data)
    print(res1, type(res1))
    
    {"1": "a", "2": "b", "3": "c"} 
    
    Python Json
    dict object
    list, tuple array
    str, unicode string
    int, long, float number
    True true
    False false
    None null
  • loads(), 将josn字符串转换为python对象

    res2 = json.loads(res1)
    print(res2, type(res2))
    
    {'1': 'a', '2': 'b', '3': 'c'} 
    
    Json Python
    object dict
    array list
    string unicode
    number(int) int, long
    number(real) float
    true True
    false False
    null None

2. dump和load

注意: dumps和loads是作用在python对象josn字符串上的, 而dump和load是作用在json文件上的

  • dump, 将数据以json的格式保存至文件

    with open('file', 'w') as f:
        json.dump(data, f)
    
  • load, 读取json文件

    with open('file', 'r') as f:
        res3 = json.load(f)
        print(res3, type(res3))
    
    {'1': 'a', '2': 'b', '3': 'c'} 
    

分析: 此处数据data为python字典, 使用json保存并读取后亦为字典; 若数据为python字符串对象使用dump保存, 则使用load读取后亦为字符串(可进一步通过loads将字符串转换为python对象)。

with open('file', 'w') as f:
    json.dump(res1, f)
    
with open('file', 'r') as f:
    res3 = json.load(f)
    print(res3, type(res3))
    print('*'*50)
    res4 = json.loads(res3)
    print(res4, type(res4))
{"1": "a", "2": "b", "3": "c"} 
**************************************************
{'1': 'a', '2': 'b', '3': 'c'} 

彩蛋

细心的同学可能发现, 在使用dumps(),将python对象转换为josn字符串后, 原本数据datakeyint类型变成了字符串类型。注意json字符串python字符串的区别, 如以下报错:

str1 = '{1:"a", 2:"b", 3:"c"}'
print(str1, type(str1))
res5 = json.loads(str1)
print(res5, type(res5))
{1:"a", 2:"b", 3:"c"} 
.......
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

还需要注意的一点是, json字符串的内部为双引号(""), 否则也会报以上错误

在这里插入图片描述

因此, 构建json字符串时需要特别注意, 正确构建方式如下:

str1 = '{"1":"a", "2":"b", "3":"c"}'
print(str1, type(str1))
res5 = json.loads(str1)
print(res5, type(res5))
{"1":"a", "2":"b", "3":"c"} 
{'1': 'a', '2': 'b', '3': 'c'} 

你可能感兴趣的:(python笔记)