确定文件是YAML还是JSON格式



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

我发现一些代码在这里有一种方法来确定一个文件是否在YAML或JSON格式?并发现如下:

import re
from pathlib import Path
commas = re.compile(r',(?=(?!["]*[sw?."!-_]*,))(?=(?![^[]*]))')
"""
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.yamlexample.json

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

对有帮助的人表示感谢。

下面的内容应该可以工作(假设文件只能是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'

最新更新