yaml数据:
python
address:
city: 北京市
postalCode: '100000'
street: 北京路123号
age: 30
cart:
- product:
name: 笔记本电脑
price: 1199.99
quantity: 2
- product:
name: 智能手机
price: 599.99
quantity: 1
children:
- age: 5
name: 小王
- age: 3
name: 小李
email: zhangsan@example.com
isMarried: false
login:
password: password123
username: zhangsan
name: 张三
phoneNumbers:
- number: '2341234'
type: home
- number: '5678901'
type: office
实现代码:
python
# -- coding:utf-8 --
import yaml
import json
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def yamlTojson(yaml_path, json_path):
# 读取YAML文件
with open(yaml_path, 'r', encoding='utf-8') as stream:
try:
# 将YAML内容转换为Python字典
data_yaml = yaml.safe_load(stream)
# 将Python字典转换为JSON字符串
data_json = json.dumps(data_yaml, ensure_ascii=False, indent=4)
# 将JSON字符串写入到JSON文件
with open(json_path, 'w', encoding='utf-8') as f:
f.write(data_json)
print(f"YAML文件'{yaml_path}'已成功转换为JSON文件'{json_path}'")
except yaml.YAMLError as exc:
print(f"YAML文件解析错误: {exc}")
if __name__ == '__main__':
jsonPath = "data2.json"
yamlPath = "data.yaml"
jsonPath = os.path.join(BASE_DIR, jsonPath)
yamlPath = os.path.join(BASE_DIR, yamlPath)
yamlTojson(yamlPath, jsonPath)
结果展示:
python
{
"address": {
"city": "北京市",
"postalCode": "100000",
"street": "北京路123号"
},
"age": 30,
"cart": [
{
"product": {
"name": "笔记本电脑",
"price": 1199.99,
"quantity": 2
}
},
{
"product": {
"name": "智能手机",
"price": 599.99,
"quantity": 1
}
}
],
"children": [
{
"age": 5,
"name": "小王"
},
{
"age": 3,
"name": "小李"
}
],
"email": "zhangsan@example.com",
"isMarried": false,
"login": {
"password": "password123",
"username": "zhangsan"
},
"name": "张三",
"phoneNumbers": [
{
"number": "2341234",
"type": "home"
},
{
"number": "5678901",
"type": "office"
}
]
}