手工准备一个JSON文件,内部包括你和你的好友共3人的信息。每个人的信息有学号、姓名、性别、座右铭。 编程解析JSON文件,将文件中的好友信息存入Python的列表中。 将列表中的内容保存到一个CSV文件中(注意,座右铭中可能包括英文逗号)。
时间: 2024-03-08 09:46:58 浏览: 30
好的,我了解了你的要求。我将提供Python代码来解析JSON文件并将其中的好友信息存入列表中,并将列表中的内容保存到CSV文件中。以下是代码:
```python
import json
import csv
# 读取JSON文件
with open('friends.json', 'r') as f:
friends_data = json.load(f)
# 将好友信息存入列表中
friends_list = []
for friend in friends_data['friends']:
friends_list.append([
friend['学号'],
friend['姓名'],
friend['性别'],
friend['座右铭']
])
# 将列表中的内容保存到CSV文件中
with open('friends.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['学号', '姓名', '性别', '座右铭'])
writer.writerows(friends_list)
```
这段代码假定你已经有一个名为 "friends.json" 的JSON文件,其中包含好友信息。JSON文件的格式应该如下所示:
```json
{
"friends": [
{
"学号": "001",
"姓名": "张三",
"性别": "男",
"座右铭": "Stay hungry, stay foolish."
},
{
"学号": "002",
"姓名": "李四",
"性别": "女",
"座右铭": "The future belongs to those who believe in the beauty of their dreams."
},
{
"学号": "003",
"姓名": "王五",
"性别": "男",
"座右铭": "Be the change you wish to see in the world."
}
]
}
```
这个JSON文件中有三个好友的信息,每个好友都有一个学号、姓名、性别和座右铭。
代码将读取JSON文件,将每个好友的信息存储为一个列表,并将这些列表存储在一个大列表中。然后,代码将使用Python的CSV模块将这个大列表写入CSV文件中。注意,我们使用 `newline=''` 参数来避免在CSV文件中出现额外的空行,并使用 `encoding='utf-8-sig'` 参数来避免在CSV文件中出现乱码。