Understand Python's json_dump(s) and json_load(s) in one article

There must be many people like me who can't tell the difference between json_dump and json_dumps, the difference between json_load and json_loads, and learn it at once today!

First of all, let's distinguish the difference between with s and without s:

This is as simple as:

        1. The ones without s are used when downloading or extracting files

        with open('./cookie/hs_cookies.json', 'a+') as fp:
            json.dump(hs_cookies,fp)

        2. As the name implies, the one with s is used when no file download is required

        hs_cookies = json.load(fp)

is it easy to understand

Then let's analyze the difference between json_dump(s)( ) and json_load(s)( ) 

json.dump(): encoding, used to convert dict type data into str type, and write to json file
json.load(): decoding, used to read data from json file

json.dumps(): convert the Python data structure to JSON, that is, convert the dict type to the str type

json.loads(): Convert the JSON-encoded string back to the Python data structure, that is, convert the str type to the dict type

Is it very easy to understand

Let's take a look at the specific code next.

json.dumps()

import json

data = {
    'name' : 'name',
    'age' : 20,
}

#  其实就是把python的数据类型转化成json的数据类型嘛
json_str = json.dumps(data,ensure_ascii=False)

 json.loads()

import json

#  用dumps()将python编码成json字符串
data = json.dumps(data)
#  用loads将json编码成python
#  其实就是把json的数据类型转化成python的数据类型嘛
print(json.loads(data))

json.dump()

import json

data = {
	'name':'name',
	'age':20,
}
#  将python编码成json放在那个文件里
#  其实就是把python的数据类型转化成json的数据类型嘛
filename = 'a.txt'
with open (filename,'w') as f:
    json.dump(data ,f)

json.load()

import json

data  = {
	'name':'name',
	'age':20
}

filename = 'a.txt'


with open (filename, encoding='utf-8') as f:
    print(json.load(f))

Well, I would like to take this opportunity to remember the difference between the two

Guess you like

Origin blog.csdn.net/weixin_42019349/article/details/130322599