You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何自动美化YAML文件并移除花括号格式?

Fix: Expand YAML Inline Dictionaries While Preserving Comments

I've run into this exact frustration before—generic YAML formatters often either leave small inline {} dictionaries untouched or strip out comments entirely, which is a pain when you need to keep your original annotations intact. Here’s a reliable solution using ruamel.yaml (a YAML library built specifically to preserve comments and formatting details that PyYAML ignores):

Step 1: Install the required library

First, grab ruamel.yaml via pip—it’s the best tool for this job because it maintains your comment structure:

pip install ruamel.yaml

Step 2: Run this custom formatting script

Create a tiny Python script to process your file. It’ll expand inline dictionaries to block-style indentation while keeping your comments and original quote formatting:

from ruamel.yaml import YAML

# Initialize YAML handler with settings to retain your file's details
yaml = YAML()
yaml.preserve_quotes = True  # Keeps your original single quotes around strings
yaml.default_flow_style = False  # Forces all dictionaries to use indented block style instead of {}

# Load the original YAML file
with open('SashaPrettifyYAML.yaml', 'r') as input_file:
    yaml_data = yaml.load(input_file)

# Write the formatted output to a new file (or overwrite the original if you're confident)
with open('formatted_SashaPrettifyYAML.yaml', 'w') as output_file:
    yaml.dump(yaml_data, output_file)

Result you’ll get

After running the script, your output file will match exactly what you wanted:

sasha_commands: # Sasha comment
sasha_command_help:
  call: sublime.command_help
  caption: 'Sasha Command: Command Help'

Why your previous tools didn’t work

  • PyYAML-based tools: PyYAML doesn’t preserve comments by default, so it would strip out your # Sasha comment line entirely. Even if you forced formatting, it often skips expanding small inline dictionaries.
  • Online formatters: Most use basic PyYAML setups or don’t prioritize expanding short inline structures, plus they risk losing comments in the process.

内容的提问来源于stack exchange,提问作者Саша Черных

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:29:46