首页 > 解决方案 > 确定文件是 YAML 还是 JSON 格式

问题描述

我正在尝试将 yaml 转换为 json。但是,在转换之前,我需要检查传入的文件是否为 yaml(此检查是强制性的)

我在Is there a way to determine if a file is in YAML or JSON format? 中找到了一些代码?并在下面找到:

import re
from pathlib import Path

commas = re.compile(r',(?=(?![\"]*[\s\w\?\.\"\!\-\_]*,))(?=(?![^\[]*\]))')
"""
Find all commas which are standalone 
 - not between quotes - comments, answers
 - not between brackets - lists
"""
file_path = Path("example_file.cfg")
signs = commas.findall(file_path.open('r').read())

return "json" if len(signs) > 0 else "yaml"

但我的输入文件不像:

example_file.cfg

我的输入要么是example.yaml要么example.json

所以我需要这样的比较example_file.cfg

如果有任何帮助,将不胜感激。

标签: pythonjsonfileyaml

解决方案


像下面这样的东西应该可以工作(假设文件只能是 json 或 yaml)

import json


def yaml_or_json(file_name):
    with open(file_name) as f:
        try:
            json.load(f)
            return 'json'
        except Exception:
            return 'yaml'

推荐阅读