写一个用python解析json文件的demo

以下是一个使用Python解析JSON文件的简单Demo:

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
import json

# 示例JSON数据(也可以从文件读取)
json_data = '''
{
"name": "John Doe",
"age": 30,
"is_student": false,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "traveling", "photography"],
"grades": {
"math": 90,
"english": 85
}
}
'''

# 方法1:解析JSON字符串
def parse_json_string():
try:
# 将JSON字符串转换为Python字典
data = json.loads(json_data)

# 访问数据
print("姓名:", data["name"])
print("年龄:", data["age"])
print("城市:", data["address"]["city"])
print("第一个爱好:", data["hobbies"][0])

except json.JSONDecodeError as e:
print("JSON解析错误:", e)

# 方法2:从文件读取并解析JSON
def parse_json_file():
try:
# 写入示例JSON到临时文件(实际使用时替换为你的JSON文件路径)
with open("example.json", "w") as f:
f.write(json_data)

# 从文件读取JSON
with open("example.json", "r") as f:
data = json.load(f)

# 打印格式化后的JSON
print("\n格式化后的JSON数据:")
print(json.dumps(data, indent=4, ensure_ascii=False))

except FileNotFoundError:
print("文件未找到")
except json.JSONDecodeError as e:
print("JSON解析错误:", e)

if __name__ == "__main__":
print("=== 解析JSON字符串 ===")
parse_json_string()

print("\n=== 解析JSON文件 ===")
parse_json_file()

运行这个Demo会:

  1. 首先解析一个JSON字符串并提取部分数据
  2. 然后将同样的JSON写入文件,再从文件读取并漂亮地打印出来

实际使用时,你只需要:

  1. json_data替换为你自己的JSON字符串
  2. 或者将example.json替换为你的JSON文件路径

注意:

  • 使用json.loads()解析JSON字符串
  • 使用json.load()从文件读取JSON
  • 使用json.dumps()将Python对象转换为格式化的JSON字符串
  • 异常处理很重要,因为JSON可能格式不正确

如果需要处理更复杂的JSON,原理是一样的,只是访问嵌套数据时需要多级字典/列表访问。

遍历打印json中的数据

以下是遍历并打印JSON中所有数据的Python代码示例,包括处理嵌套的字典和列表:

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
import json

def print_json_data(data, indent=0):
"""
递归打印JSON中的所有数据
:param data: 要打印的JSON数据(Python字典或列表)
:param indent: 当前缩进级别
"""
# 缩进字符串
indent_str = " " * indent

if isinstance(data, dict):
for key, value in data.items():
# 如果是字典,打印键然后递归处理值
print(f"{indent_str}{key}: ", end="")
if isinstance(value, (dict, list)):
print() # 换行
print_json_data(value, indent + 4)
else:
print(value) # 直接打印基本类型值
elif isinstance(data, list):
for index, item in enumerate(data):
# 如果是列表,打印索引然后递归处理项
print(f"{indent_str}[{index}]: ", end="")
if isinstance(item, (dict, list)):
print() # 换行
print_json_data(item, indent + 4)
else:
print(item) # 直接打印基本类型项
else:
# 基本数据类型直接打印
print(f"{indent_str}{data}")

# 示例JSON数据
json_data = '''
{
"name": "John Doe",
"age": 30,
"is_student": false,
"address": {
"street": "123 Main St",
"city": "New York",
"coordinates": [40.7128, -74.0060]
},
"hobbies": ["reading", "traveling", "photography"],
"grades": {
"math": 90,
"english": 85
},
"contacts": [
{
"type": "email",
"value": "john@example.com"
},
{
"type": "phone",
"value": "123-456-7890"
}
]
}
'''

# 解析JSON
try:
data = json.loads(json_data)
print("=== 完整JSON数据遍历输出 ===")
print_json_data(data)
except json.JSONDecodeError as e:
print("JSON解析错误:", e)

输出结果示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
=== 完整JSON数据遍历输出 ===
name: John Doe
age: 30
is_student: False
address:
street: 123 Main St
city: New York
coordinates:
[0]: 40.7128
[1]: -74.006
hobbies:
[0]: reading
[1]: traveling
[2]: photography
grades:
math: 90
english: 85
contacts:
[0]:
type: email
value: john@example.com
[1]:
type: phone
value: 123-456-7890

如果你想从文件读取JSON并遍历,可以这样修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 从文件读取JSON并遍历
def traverse_json_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
print_json_data(data)
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到")
except json.JSONDecodeError as e:
print("JSON解析错误:", e)

# 使用示例
traverse_json_file('data.json')

这个遍历函数可以处理:

  • 嵌套的字典和列表
  • 所有基本数据类型(字符串、数字、布尔值、null)
  • 保持层次结构的缩进格式,方便阅读

如果需要特定格式的输出,可以调整print_json_data函数中的打印逻辑。

json遍历列表

在Python中遍历JSON中的列表时,通常需要先解析JSON数据(转换为Python对象),然后根据数据结构进行遍历。以下是几种常见情况的代码示例:

1. 简单列表遍历

当JSON数据是一个简单列表时:

1
2
3
4
5
6
7
8
9
10
11
import json

json_data = '["apple", "banana", "cherry"]'

# 解析JSON
data = json.loads(json_data)

# 遍历列表
print("=== 简单列表遍历 ===")
for i, item in enumerate(data):
print(f"索引 {i}: {item}")

输出:

1
2
3
4
=== 简单列表遍历 ===
索引 0: apple
索引 1: banana
索引 2: cherry

2. 嵌套列表遍历

当JSON中有嵌套列表时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import json

json_data = '''
{
"fruits": ["apple", "banana"],
"vegetables": ["carrot", "potato"],
"nested_list": [
[1, 2, 3],
["a", "b", "c"]
]
}
'''

data = json.loads(json_data)

print("=== 嵌套列表遍历 ===")
for key, value in data.items():
if isinstance(value, list):
print(f"{key}:")
for i, item in enumerate(value):
if isinstance(item, list): # 如果是嵌套列表
print(f" 子列表 {i}: {', '.join(map(str, item))}")
else:
print(f" - {item}")

输出:

1
2
3
4
5
6
7
8
9
10
=== 嵌套列表遍历 ===
fruits:
- apple
- banana
vegetables:
- carrot
- potato
nested_list:
子列表 0: 1, 2, 3
子列表 1: a, b, c

3. 列表中包含字典

当列表中的元素是字典时:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import json

json_data = '''
{
"students": [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 22},
{"name": "Charlie", "age": 21}
]
}
'''

data = json.loads(json_data)

print("=== 列表中包含字典 ===")
for student in data["students"]:
print(f"姓名: {student['name']}, 年龄: {student['age']}")

输出:

1
2
3
4
=== 列表中包含字典 ===
姓名: Alice, 年龄: 20
姓名: Bob, 年龄: 22
姓名: Charlie, 年龄: 21

4. 从文件读取JSON并遍历列表

从JSON文件中读取并遍历列表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import json

# 假设有一个data.json文件,内容如下:
'''
{
"products": [
{"id": 1, "name": "Laptop", "price": 999},
{"id": 2, "name": "Phone", "price": 699},
{"id": 3, "name": "Tablet", "price": 499}
]
}
'''

with open('data.json', 'r') as f:
data = json.load(f)

print("=== 从文件读取JSON列表 ===")
for product in data["products"]:
print(f"ID: {product['id']}, 名称: {product['name']}, 价格: ${product['price']}")

5. 使用递归处理复杂结构

对于深度嵌套的JSON结构:

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
import json

def traverse_list(lst, level=0):
indent = " " * level
for i, item in enumerate(lst):
if isinstance(item, list):
print(f"{indent}列表[{i}]:")
traverse_list(item, level + 1)
elif isinstance(item, dict):
print(f"{indent}列表[{i}]: (字典)")
traverse_dict(item, level + 1)
else:
print(f"{indent}列表[{i}]: {item}")

def traverse_dict(dct, level=0):
indent = " " * level
for key, value in dct.items():
if isinstance(value, dict):
print(f"{indent}{key}: (字典)")
traverse_dict(value, level + 1)
elif isinstance(value, list):
print(f"{indent}{key}: (列表)")
traverse_list(value, level + 1)
else:
print(f"{indent}{key}: {value}")

json_data = '''
{
"data": [
{"name": "item1", "values": [1, 2, 3]},
{"name": "item2", "values": [4, 5, [6, 7]]},
[8, 9, {"a": 10, "b": 11}]
]
}
'''

data = json.loads(json_data)
traverse_dict(data)

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
data: (列表)
列表[0]: (字典)
name: item1
values: (列表)
列表[0]: 1
列表[1]: 2
列表[2]: 3
列表[1]: (字典)
name: item2
values: (列表)
列表[0]: 4
列表[1]: 5
列表[2]:
列表[0]: 6
列表[1]: 7
列表[2]: (列表)
列表[0]: 8
列表[1]: 9
列表[2]: (字典)
a: 10
b: 11

关键点总结:

  1. 使用 json.loads() 解析JSON字符串,或 json.load() 从文件读取
  2. 使用 isinstance() 检查数据类型(listdict
  3. 对于简单列表,直接使用 for 循环遍历
  4. 对于嵌套结构,可以使用递归函数处理
  5. 使用缩进来显示层级关系,方便调试和理解数据结构

python创建目录 然后写一个文件demo

以下是一个完整的Python示例,展示如何创建目录(如果不存在)并在其中写入文件:

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
import os

def create_directory_and_write_file(directory, filename, content):
"""
创建目录(如果不存在)并写入文件

:param directory: 要创建的目录路径
:param filename: 要创建的文件名
:param content: 要写入文件的内容
"""
try:
# 1. 创建目录(如果不存在)
os.makedirs(directory, exist_ok=True)
print(f"目录 '{directory}' 已创建或已存在")

# 2. 拼接完整文件路径
filepath = os.path.join(directory, filename)

# 3. 写入文件
with open(filepath, 'w', encoding='utf-8') as file:
file.write(content)
print(f"文件 '{filename}' 已成功写入到 '{directory}'")

# 4. 返回写入的完整路径
return filepath

except Exception as e:
print(f"操作失败: {e}")
return None

# 使用示例
if __name__ == "__main__":
# 设置目录和文件信息
target_dir = "example_dir" # 可以是相对路径或绝对路径
file_name = "demo.txt"
file_content = """这是一个示例文件
创建时间:2023-11-15
这是Python自动创建和写入的文件内容。

你可以在这里写入任何文本内容:
- 列表项1
- 列表项2
- 列表项3
"""

# 调用函数
created_file = create_directory_and_write_file(target_dir, file_name, file_content)

# 验证结果
if created_file:
print("\n验证写入内容:")
with open(created_file, 'r', encoding='utf-8') as f:
print(f.read())

关键点说明:

  1. 目录创建

    • os.makedirs(directory, exist_ok=True) 会递归创建所有不存在的父目录
    • exist_ok=True 参数确保目录已存在时不会报错
  2. 路径拼接

    • 使用 os.path.join() 可以跨平台正确处理路径分隔符(Windows用\,Linux/Mac用/
  3. 文件写入

    • 使用 with open() as file 上下文管理器自动处理文件关闭
    • 指定 encoding='utf-8' 确保正确处理中文等非ASCII字符
  4. 错误处理

    • 捕获可能出现的异常(如权限不足、磁盘空间不足等)

进阶用法:

  • 如果要写入JSON数据:

    1
    2
    3
    4
    import json

    data = {"name": "张三", "age": 25, "hobbies": ["阅读", "编程"]}
    create_directory_and_write_file("json_example", "data.json", json.dumps(data, ensure_ascii=False, indent=2))
  • 如果要追加内容到已存在文件:

    1
    2
    with open(filepath, 'a', encoding='utf-8') as file:  # 注意模式改为 'a'
    file.write("\n这是追加的内容")

这个示例涵盖了文件操作中最常见的需求,你可以根据需要修改目录路径、文件名和内容。

将/替换乘_

如果你想将文件路径中的斜杠 / 替换为下划线 _(例如用于生成安全的文件名),可以使用 Python 的字符串替换方法 str.replace()。以下是几种常见情况的处理方法:


1. 替换路径中的 /_(适用于文件名)

如果路径是类似 "path/to/file.txt",你想转换成 "path_to_file.txt"

1
2
3
path = "path/to/file.txt"
safe_name = path.replace("/", "_")
print(safe_name) # 输出: path_to_file.txt

2. 处理 Windows 路径(\ 替换为 _

Windows 路径使用反斜杠 \,可以用 replace("\\", "_")

1
2
3
windows_path = r"C:\Users\Admin\file.txt"
safe_name = windows_path.replace("\\", "_")
print(safe_name) # 输出: C:_Users_Admin_file.txt

注意r"..." 是原始字符串,避免 \ 被转义。


3. 同时替换 /\(跨平台兼容)

如果路径可能包含 /\,可以先用 os.path.normpath 标准化路径,再替换:

1
2
3
4
5
6
import os

path = "path/to\\file.txt" # 混合斜杠
normalized_path = os.path.normpath(path) # 标准化路径(取决于操作系统)
safe_name = normalized_path.replace(os.sep, "_") # os.sep 是当前系统的路径分隔符
print(safe_name) # 在 Windows 输出: path_to_file.txt

4. 处理 URL 或特殊路径

如果路径是 URL(如 "https://example.com/file"),你可能只想替换路径部分:

1
2
3
4
5
6
7
8
9
10
11
url = "https://example.com/path/to/file"
safe_name = url.replace("/", "_") # 简单替换(但会替换所有 `/`)
print(safe_name) # 输出: https:__example.com_path_to_file

# 更精细的处理(仅替换路径部分)
from urllib.parse import urlparse

parsed = urlparse(url)
path_safe = parsed.path.replace("/", "_")
safe_name = f"{parsed.scheme}://{parsed.netloc}{path_safe}"
print(safe_name) # 输出: https://example.com_path_to_file

5. 完整示例:创建目录并写入文件(替换 /_

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os

def create_safe_filename(path):
"""将路径中的 `/` 或 `\` 替换为 `_`"""
return os.path.normpath(path).replace(os.sep, "_")

# 示例
original_path = "data/json/files/example.json"
safe_filename = create_safe_filename(original_path)
print(safe_filename) # 输出: data_json_files_example.json

# 创建目录并写入文件
os.makedirs("output", exist_ok=True)
with open(f"output/{safe_filename}", "w") as f:
f.write('{"key": "value"}')
print("文件已保存!")

总结

方法 说明 示例
path.replace("/", "_") 替换 / "a/b/c""a_b_c"
path.replace("\\", "_") 替换 \ "a\b\c""a_b_c"
os.path.normpath(path).replace(os.sep, "_") 跨平台替换 "a/b\c""a_b_c"
urllib.parse + replace 处理 URL "https://a/b""https://a_b"

你可以根据需求选择合适的方法!

取字符串1到3位

在 Python 中,要提取字符串的第 1 到第 3 个字符(即前 3 个字符),可以使用 字符串切片(String Slicing)。以下是几种常见的方法:


方法 1:直接切片 [0:3]

Python 的字符串索引从 0 开始,所以 [0:3] 表示从第 1 个字符到第 3 个字符(不包括第 4 个字符):

1
2
3
s = "abcdef"
substring = s[0:3] # 取第1~3位
print(substring) # 输出: "abc"

说明

  • s[0] → 第 1 个字符 ('a')
  • s[1] → 第 2 个字符 ('b')
  • s[2] → 第 3 个字符 ('c')
  • s[0:3] → 取 s[0]s[1]s[2](不包括 s[3]

方法 2:省略起始索引 [:3]

如果起始索引是 0,可以简写为 [:3]

1
2
3
s = "abcdef"
substring = s[:3] # 等同于 s[0:3]
print(substring) # 输出: "abc"

方法 3:处理字符串长度不足的情况

如果要确保即使字符串长度 <3 也不会报错:

1
2
3
s = "ab"
substring = s[:3] # 如果字符串长度 <3,则返回整个字符串
print(substring) # 输出: "ab"

方法 4:使用 str.ljust() 填充(可选)

如果希望不足 3 位时用特定字符(如空格)填充:

1
2
3
s = "ab"
substring = s[:3].ljust(3, '-') # 不足3位时用 '-' 填充
print(substring) # 输出: "ab-"

总结

方法 代码 说明
直接切片 s[0:3] 最标准写法
简写切片 s[:3] 省略 0,更简洁
处理短字符串 s[:3] 长度 <3 时不会报错
填充不足位数 s[:3].ljust(3, '-') 不足 3 位时用 - 补全

适用场景

  • 文件名处理:取前 3 个字符作为短标识。
  • 数据截断:如只显示用户名前 3 个字。
  • 编码处理:如提取固定长度的前缀。

希望这几种方法能帮到你! 😊