如何在Python中读取和写入JSON文件

In this tutorial we will go through the process of reading and writing JSON files in Python. While sending or receiving data between server it can only be text, so JSON (JavaScript Object Notation) is a data format used to convert JavaScript object to JSON and send it to the server.

在本教程中,我们将介绍用Python读写JSON文件的过程。 在服务器之间发送或接收数据时,它只能是文本,因此JSON(JavaScript对象表示法)是一种数据格式,用于将JavaScript对象转换为JSON并将其发送到服务器。

Python has a module json which is used in doing manipulation on json files and for creating new json files. While working with Python json files exist as a string, that means anytime we are working with Python every json file is considered as a string. In JSON, variables must be of one of the following data types.

Python有一个 json 模块 ,用于对json文件进行操作并创建新的json文件。 使用Python json文件时,它以字符串形式存在,这意味着在我们使用Python的任何时候,每个json文件都被视为字符串。 在JSON中,变量必须是以下数据类型之一。

  • String

  • Number

  • Object (JSON object)

    对象(JSON对象)

  • Array

    数组

  • Boolean

    布尔型

  • null

    空值

When these data types are converted in python for reading they are converted to python equivalent data type according to the following table: 

在python中将这些数据类型转换为可读取时,根据下表将它们转换为python等效数据类型:

PythonJSON equivalent
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull
Python 相当于JSON
字典 目的
列表,元组 数组
力量
整数,浮点数
真正 真正
没有 空值

在Python中读取JSON文件 (Reading JSON File in Python)

For reading json file in python we can use the json.loads() method from json module. Here is a simple example : 

为了在python中读取json文件,我们可以使用json模块中的json.loads()方法。 这是一个简单的例子:

import json
student = '{"name": "Rajesh", "roll" : "52", "subject": ["English", "Science"]}'
student_loaded = json.loads(student)
print(student_loaded)
print(student_loaded['roll'])

Here the student string is representing the json object which is getting converted into a python dictionary according to the above table.

这里的学生字符串表示根据上表转换为python字典的json对象。

Output:

输出:

{‘name’: ‘Rajesh’, ‘roll’: ’52’, ‘subject’: [‘English’, ‘Science’]}
52

{ 'name' : 'Rajesh' , 'roll' : '52' , 'subject' :[ 'English' , 'Science' ]} 52

Here we have taken the json file in a python string which is not used practically, In practice we will read json file, so while reading instead of using the method loads method load is used to convert json into python.

在这里,我们将json文件放入一个实际上不使用的python字符串中,在实践中,我们将读取json文件,因此在读取而不是使用方法load时,使用load方法将json转换为python。

Now if our student.json file looks something like this 

现在,如果我们的student.json文件看起来像这样

{
    "name": "Rajesh", 
    "roll" : "52", 
    "subject": ["English", "Science"]
}

Then to read this file the python code will look like:

然后要读取此文件,python代码将如下所示:

import json
 
with open('student.json') as json_file :
    student_loaded = json.load(json_file)
 
print(student_loaded)
print(student_loaded['subject'])

Output:

输出:

{‘name’: ‘Rajesh’, ‘roll’: ’52’, ‘subject’: [‘English’, ‘Science’]} [‘English’, ‘Science’]

{'name':'Rajesh','roll':'52','subject':['English','Science']} ['English','Science']

用Python写入JSON文件 (Writing to JSON File in Python)

The same table will now be used to convert python data types to json equivalents. To convert a python dict to a json object we will use the method dumps from the json module. It will return a string which will be converted into json format. The python code looks as below: 

现在,该表将用于将python数据类型转换为json等效项。 要将python dict转换为json对象,我们将使用json模块中的方法转储。 它将返回一个字符串,该字符串将转换为json格式。 python代码如下所示:

import json
 
student = {
    'name': 'Rajesh',
    'roll': 52,
    'subject': ['English', 'Science']
}
 
student_dumped = json.dumps(student)
 
print(student_dumped)
print(type(student_dumped))

In the above code the student is a dictionary and the result after performing the dumps operation is a string which is evident from the output.

在上面的代码中,学生是一个字典,执行转储操作后的结果是一个字符串,从输出中可以明显看出。

{“name”: “Rajesh”, “roll”: 52, “subject”: [“English”, “Science”]} <class ‘str’>

{“名称”:“ Rajesh”,“卷”:52,“主题”:[“英语”,“科学”]} <class'str'>

As in the case of loads, while writing to a json file instead of using dumps we simply use dump for the same.

与加载的情况一样,在写入json文件而不是使用转储时,我们仅对转储使用相同的内容。

import json
 
student = {
    'roll': 52,
    'name': 'Rajesh',
    'subject': ['English', 'Science']
}
 
with open('student.json','w') as student_dumped :
    json.dump(student,student_dumped)

This will create(if not present) or modify the student.json file to:

这将创建(如果不存在)或将student.json文件修改为:

{“roll”: 52, “name”: “Rajesh”, “subject”: [“English”, “Science”]}

{“ roll”: 52 ,“ name”: “ Rajesh” ,“ subject”:[ “ English” , “ Science” ]}

In the dump method the first is the python dict and second is the python file as argument. As we can see in the above output, dump does not write file in readable format. We can use parameters in the dump method to make it more readable.

在dump方法中,第一个是python dict,第二个是python文件作为参数。 从上面的输出中可以看到,dump不会以可读格式写入文件。 我们可以在转储方法中使用参数以使其更具可读性。

indent: used for indentation in json file 

缩进:用于json文件中的缩进

sort_keys: used for sorting keys in ascending order.

sort_keys:用于对密钥进行升序排序。

By default indent value is None and sort_keys is False.

默认情况下,缩进值为None,sort_keys为False。

import json
 
student = {
    'roll': 52,
    'name': 'Rajesh',
    'subject': ['English', 'Science']
}
 
with open('student.json','w') as student_dumped :
    json.dump(student,student_dumped,indent = 4,sort_keys = True)

Using the above parameters the output is changed to:

使用以上参数,输出更改为:

{
    “name”: “Rajesh”,
    “roll”: 52,
    “subject”: [
        “English”,
        “Science”
    ]
}

{ “名称”: “ Rajesh” , “滚动”: 52 , “学科”: [ “英语” , “科学” ] }

I hope you got idea about how to read and write to json file in python. Comment down below if still you have any queries.

我希望您对如何在python中读取和写入json文件有所了解。 如果您仍有任何疑问,请在下面注释掉。

翻译自: https://www.thecrazyprogrammer.com/2019/11/read-and-write-to-json-file-in-python.html

  • 0
    点赞
  • 0
    评论
  • 8
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值