Python - 附加到 JSON 文件

位置:首页>文章>详情   分类: Python教程 > 编程技术   阅读(343)   2024-05-15 10:55:30

学习读取 JSON 文件并用 Python 将 JSON 数据附加到文件中

1. 附加到 JSON 文件的步骤

在 Python 中,将 JSON 附加到文件包括以下步骤:

  • 在 Python dictlist 对象中读取 JSON。
  • 通过修改将 JSON 附加到 dict(或 list)对象。
  • 将更新后的dict(或list)对象写入原始文件。

请参阅以下文章以了解如何从文件中读取 JSON在 Python 中将 JSON 写入文件

2. 使用 Python 列表附加到 JSON 数组

users.json 文件有一个包含 2 个用户的列表。我们将向其附加第三个用户。

[
    {
        "Name": "Person_1",
        "Age": 11,
        "Email": "11@gmail.com"
    },
    {
        "Name": "Person_2",
        "Age": 22,
        "Email": "22@gmail.com"
    }
]
import json
from os import path
 
filename = 'c:/temp/users.json'
listObj = []
 
# Check if file exists
if path.isfile(filename) is False:
  raise Exception("File not found")
 
# Read JSON file
with open(filename) as fp:
  listObj = json.load(fp)
 
# Verify existing list
print(listObj)
print(type(listObj))
 
listObj.append({
  "Name": "Person_3",
  "Age": 33,
  "Email": "33@gmail.com"
})
 
# Verify updated list
print(listObj)
 
with open(filename, 'w') as json_file:
    json.dump(listObj, json_file, 
                        indent=4,  
                        separators=(',',': '))
 
print('Successfully appended to the JSON file')

更新后的 JSON 文件为:

[
    {
        "Name": "Person_1",
        "Age": 11,
        "Email": "11@gmail.com"
    },
    {
        "Name": "Person_2",
        "Age": 22,
        "Email": "22@gmail.com"
    },
    {
        "Name": "Person_3",
        "Age": 33,
        "Email": "33@gmail.com"
    }
]

3. 使用 Python 字典附加到 JSON 对象

users.json 文件有一个包含 2 个用户的列表。我们将附加一个新属性 role 并修改现有属性 Age

{
	"Name": "Person_1",
	"Age": 11,
	"Email": "11@gmail.com"
}
import json
from os import path
 
filename = 'c:/temp/users.json'
dictObj = []
 
# Check if file exists
if path.isfile(filename) is False:
  raise Exception("File not found")
 
# Read JSON file
with open(filename) as fp:
  dictObj = json.load(fp)
 
# Verify existing dict
print(dictObj)

print(type(dictObj))
 
dictObj.update({"Age": 12,"Role": "Developer"})
 
# Verify updated dict
print(dictObj)
 
with open(filename, 'w') as json_file:
    json.dump(dictObj, json_file, 
                        indent=4,  
                        separators=(',',': '))
 
print('Successfully written to the JSON file')

更新后的 JSON 文件为:

{
    "Name": "Person_1",
    "Age": 12,
    "Email": "11@gmail.com",
    "Role": "Developer"
}

4. AttributeError: ‘dict’ object has no attribute ‘append’

如果从 json.load() 方法读取的 JSON 对象是 dict 类型,我们可能会得到这个错误。

第一个示例读取 JSON 列表 [...],因此加载的对象的类型为 list。如果我们正在读取一个包含 JSON 对象 {...} 的文件,那么加载的对象将是 dictionary 类型,上面的代码将给出 AttributeError在调用 list 操作时。

{'Name': 'Person_1', 'Age': 11, 'Email': '11@gmail.com'}
<class 'dict'>
Traceback (most recent call last):
  File "C:\temp\temp.py", line 20, in <module>
    listObj.append({
AttributeError: 'dict' object has no attribute 'append'

要修复此错误,请注意您从 JSON 文件中读取的 JSON 结构。

  • 将 JSON 对象读取为 Python dict 对象。
  • 读取 JSON 数组到 Python list 对象。

快乐学习!!

地址:https://www.cundage.com/article/append-json-to-file.html

相关阅读

学习读取 JSON 文件并用 Python 将 JSON 数据附加到文件中。 1. 附加到 JSON 文件的步骤 在 Python 中,将 JSON 附加到文件包括以下步骤:
学习读取 JSON 文件并用 Python 将 JSON 数据附加到文件中。 1. 附加到 JSON 文件的步骤 在 Python 中,将 JSON 附加到文件包括以下步骤: 在 Python ...
OrderedDict 维护添加到字典中的项目的插入顺序。在迭代或序列化时也会保留项目的顺序。 1.Python OrderedDict例子 OrderedDict 是 python 集合模块的...
Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印()
学习使用 Python httplib2 模块。 超文本传输协议 (HTTP) 是分布式协作超媒体信息系统的应用协议。 HTTP 是万维网数据通信的基础。 Python httplib2 模块提...
阅读、理解和练习这些 Python 示例,以更好地理解 Python 语言。这些简单的 Python 程序将帮助我们理解 Python 的基本编程概念。 此页面上的所有程序都经过测试,应该可以在...
阅读、理解和练习这些 Python 示例,以更好地理解 Python 语言。这些简单的 Python 程序将帮助我们理解 Python 的基本编程概念
Learn to use Python 打印() function to 将 Python 程序或 Python 脚本的打印输出重定向到文件. 1. 使用 文件 参数打印到文件 打印() 函数接...
Python 集是独特元素的无序集合。了解 Python 中的 Set datatype,创建和修改 Set 以及其他有用的 Set 操作。 1. 什么是集合 Python 中的集合是: 独特的...
1. Python 内置函数 蟒蛇绝对() 返回整数的绝对值,float;和复数的大小。 Python any() 函数 检查 Iterable 的至少一个元素是否为 True。 Python ...