【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"
        }
    ]
}
相关推荐
DougLiang40 分钟前
关于easyexcel动态下拉选问题处理
java·开发语言
全职计算机毕业设计1 小时前
基于Java Web的校园失物招领平台设计与实现
java·开发语言·前端
5:002 小时前
云备份项目
linux·开发语言·c++
Eiceblue2 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550402 小时前
初级程序员入门指南
javascript·python·算法
笨笨马甲2 小时前
Qt Quick模块功能及架构
开发语言·qt
程序员的世界你不懂2 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
夜晚回家3 小时前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS3143 小时前
C++动态规划-01背包
开发语言·c++·动态规划
前端页面仔3 小时前
易语言是什么?易语言能做什么?
开发语言·安全