File size: 3,530 Bytes
710b71f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import json
import os
from typing import Any

def save_to_json(data: Any, file_path: str, indent: int = 4) -> None:
    """
    将数据保存到JSON文件中。

    Args:
        data (Any): 要保存的数据,通常是字典或列表。
        file_path (str): 保存JSON文件的路径。
        indent (int): 缩进级别,默认为4,用于格式化JSON文件。

    Raises:
        IOError: 当文件无法写入时抛出异常。
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=indent)
        print(f"数据已成功保存到 {file_path}")
    except IOError as e:
        print(f"保存到文件 {file_path} 失败: {e}")
        exit()

def load_from_json(file_path: str) -> Any:
    """
    从JSON文件中读取数据。

    Args:
        file_path (str): 要读取的JSON文件路径。

    Returns:
        Any: 读取的JSON数据,通常是字典或列表。

    Raises:
        IOError: 当文件无法读取时抛出异常。
        json.JSONDecodeError: 当JSON格式错误时抛出异常。
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        print(f"数据已成功从 {file_path} 加载")
        return data
    except (IOError, json.JSONDecodeError) as e:
        print(f"读取文件 {file_path} 失败: {e}")
        exit()

def append_to_json(data: Any, file_path: str) -> None:
    """
    向现有的JSON文件追加数据。如果文件不存在,则创建新文件。

    Args:
        data (Any): 要追加的数据。
        file_path (str): JSON文件的路径。

    Raises:
        IOError: 当文件无法写入时抛出异常。
    """
    existing_data = load_from_json(file_path) or []
    
    if isinstance(existing_data, list):
        existing_data.append(data)
    else:
        print(f"文件 {file_path} 的内容不是列表,无法追加数据。")
        exit()
    
    save_to_json(existing_data, file_path)

def is_json(file_path: str) -> bool:
    """
    检查一个文件是否为有效的JSON文件。

    Args:
        file_path (str): 文件路径。

    Returns:
        bool: 如果文件是有效的JSON文件,返回True,否则返回False。
    """
    if not os.path.exists(file_path):
        return False

    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            json.load(f)
        return True
    except (IOError, json.JSONDecodeError):
        return False

def pretty_print_json(data: Any) -> None:
    """
    以漂亮格式打印JSON数据。

    Args:
        data (Any): 要打印的JSON数据,通常是字典或列表。
    """
    print(json.dumps(data, ensure_ascii=False, indent=4))

def print_json_by_index(file_path: str, index: int) -> None:
    """
    打印JSON文件中的第index条数据。

    Args:
        file_path (str): JSON文件的路径。
        index (int): 要打印的条目索引,从0开始。

    Raises:
        IndexError: 如果索引超出列表范围,将抛出异常。
    """
    data = load_from_json(file_path)
    
    if data is None:
        print("无法加载数据")
        return

    if not isinstance(data, list):
        print("JSON文件的内容不是列表格式,无法按索引访问")
        return

    try:
        item = data[index]
        pretty_print_json(item)
    except IndexError:
        print(f"索引 {index} 超出范围。该JSON文件仅包含 {len(data)} 条数据。")