📜  使用Python附加到 JSON 文件

📅  最后修改于: 2022-05-13 01:54:57.194000             🧑  作者: Mango

使用Python附加到 JSON 文件

JSON 的完整形式是 JavaScript Object Notation。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 JSON 的内置包支持 JSON。要使用此功能,我们在Python脚本中导入 JSON 包。 JSON中的文本是通过quoted-string完成的,该字符串包含{}内键值映射中的值。

使用的功能:

  • json.loads(): json.loads()函数存在于Python内置的“json”模块中。该函数用于解析 JSON字符串。

  • json.dumps(): json.dumps()函数存在于Python内置的“json”模块中。该函数用于将Python对象转换为 JSON字符串。

  • update():此方法使用来自另一个字典对象或可迭代键/值对的元素更新字典。

示例 1:更新 JSON字符串。

Python3
# Python program to update
# JSON
 
 
import json
  
# JSON data:
x =  '{ "organization":"GeeksForGeeks",
        "city":"Noida",
        "country":"India"}'
 
# python object to be appended
y = {"pin":110096}
 
# parsing JSON string:
z = json.loads(x)
  
# appending the data
z.update(y)
 
# the result is a JSON string:
print(json.dumps(z))


Python3
# Python program to update
# JSON
 
 
import json
 
 
# function to add to JSON
def write_json(new_data, filename='data.json'):
    with open(filename,'r+') as file:
          # First we load existing data into a dict.
        file_data = json.load(file)
        # Join new_data with file_data inside emp_details
        file_data["emp_details"].append(new_data)
        # Sets file's current position at offset.
        file.seek(0)
        # convert back to json.
        json.dump(file_data, file, indent = 4)
 
    # python object to be appended
y = {"emp_name":"Nikhil",
     "email": "nikhil@geeksforgeeks.org",
     "job_profile": "Full Time"
    }
     
write_json(y)


输出:

示例 2:更新 JSON 文件。假设 JSON 文件如下所示。

python-json

我们想在emp_details之后添加另一个 JSON 数据。下面是实现。

Python3

# Python program to update
# JSON
 
 
import json
 
 
# function to add to JSON
def write_json(new_data, filename='data.json'):
    with open(filename,'r+') as file:
          # First we load existing data into a dict.
        file_data = json.load(file)
        # Join new_data with file_data inside emp_details
        file_data["emp_details"].append(new_data)
        # Sets file's current position at offset.
        file.seek(0)
        # convert back to json.
        json.dump(file_data, file, indent = 4)
 
    # python object to be appended
y = {"emp_name":"Nikhil",
     "email": "nikhil@geeksforgeeks.org",
     "job_profile": "Full Time"
    }
     
write_json(y)

输出:

python-附加-json