【python】yaml转成json

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

yaml数据:

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

实现代码:

# -- 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)

结果展示:

{
    "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"
        }
    ]
}
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔都吴所谓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值