【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"
        }
    ]
}
相关推荐
xingshanchang2 分钟前
PyTorch 不支持旧GPU的异常状态与解决方案:CUDNN_STATUS_NOT_SUPPORTED_ARCH_MISMATCH
人工智能·pytorch·python
不想写bug呀2 小时前
多线程案例——单例模式
java·开发语言·单例模式
我不会写代码njdjnssj3 小时前
网络编程 TCP UDP
java·开发语言·jvm
费弗里3 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(1)
python·dash
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python