【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: [email protected]
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": "[email protected]",
    "isMarried": false,
    "login": {
        "password": "password123",
        "username": "zhangsan"
    },
    "name": "张三",
    "phoneNumbers": [
        {
            "number": "2341234",
            "type": "home"
        },
        {
            "number": "5678901",
            "type": "office"
        }
    ]
}
相关推荐
农夫山泉2号20 分钟前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
Aric_Jones1 小时前
lua入门语法,包含安装,注释,变量,循环等
java·开发语言·git·elasticsearch·junit·lua
Akiiiira1 小时前
【日撸 Java 三百行】Day 12(顺序表(二))
java·开发语言
ZHOU_WUYI1 小时前
Flask Docker Demo 项目指南
python·docker·flask
EndingCoder1 小时前
2025年JavaScript性能优化全攻略
开发语言·javascript·性能优化
码上淘金6 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo6 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552876 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子6 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174297 小时前
Python Day23 学习
python·学习