【python】yaml转成json

姊妹篇:【python】json转成成yaml

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"
        }
    ]
}
相关推荐
哪 吒几秒前
华为OD机试 - 冠亚军排名(Python/JS/C/C++ 2024 E卷 100分)
javascript·python·华为od
F_D_Z22 分钟前
【Python】数据可视化之聚类图
python·信息可视化·聚类
DanCheng-studio1 小时前
毕业设计项目 大数据电影数据分析与可视化系统(源码+论文)
python·毕业设计·毕设
程序猿阿伟2 小时前
《C++音频降噪秘籍:让声音纯净如初》
开发语言·c++·网络协议
暮毅2 小时前
四、Drf认证组件
python·django·drf
Tech_gis3 小时前
C++ 观察者模式
开发语言·c++·观察者模式
卑微求AC3 小时前
继电器原理及应用
c语言·开发语言·51单片机·嵌入式
曳渔3 小时前
Java-数据结构-反射、枚举 |ू・ω・` )
java·开发语言·数据结构·算法
laocooon5238578863 小时前
java 模拟多人聊天室,服务器与客户机
java·开发语言
风槐啊3 小时前
六、Java 基础语法(下)
android·java·开发语言