yaml.safe_dump(json.loads(raw)) is the one-line answer to "json to yaml" in Python, and it works until you diff the result. PyYAML alphabetizes your keys, folds long lines at column 80, escapes every non-ASCII character and glues list items to their parent key. Each default has a fix.
The worse trap shows up a week later. PyYAML correctly writes the country code Norway as 'no', a reviewer deletes the "noisy" quotes, and the next load returns False.
TL;DR
yaml.safe_dump(data, sort_keys=False, width=4096, allow_unicode=True)fixes sorted keys, folded lines and escaped Unicode. Recipe 8 bundles it with list indent and multiline strings into onejson_to_yamlhelper.- PyYAML quotes strings like
"no"and"0123"to keep them strings. Strip those quotes and they load asFalseand83.- Going back to JSON,
safe_loadkeeps the last duplicate key without a warning, refuses files with---separators, and returns dates thatjson.dumpsrejects.
1. The one-liner alphabetizes your config, and sort_keys=False fixes it
safe_dump sorts keys by default. The sort_keys argument exists since PyYAML 5.1; older versions always sort. Here is a deployment-shaped config where name is first on purpose, dumped both ways:
import json import yaml raw = '{"name": "web", "image": "nginx:1.27", "replicas": 3, "ports": [80, 443], "env": {"REGION": "eu-west-1", "LOG_LEVEL": "info"}}' data = json.loads(raw) print(yaml.safe_dump(data)) print(yaml.safe_dump(data, sort_keys=False)) env: LOG_LEVEL: info REGION: eu-west-1 image: nginx:1.27 name: web ports: - 80 - 443 replicas: 3 name: web image: nginx:1.27 replicas: 3 ports: - 80 - 443 env: REGION: eu-west-1 LOG_LEVEL: info Python dicts keep insertion order and json.loads builds them in document order, so nothing else is needed. Pass sort_keys=False on every dump, because reviewers read YAML top to bottom and expect name or apiVersion first.
2. width=4096 stops line folding, allow_unicode=True stops escapes
PyYAML folds long strings onto continuation lines once they pass 80 columns, and it writes non-ASCII characters as escape sequences. Set width above any line you will ever have, and turn on allow_unicode.
A long run: command from a GitHub Actions step shows both problems at once. The first print uses the defaults, the second the tuned arguments:
import json import yaml data = json.loads("""{ "owner": "Zo\\u00eb M\\u00fcller", "run": "docker build --pull --build-arg VERSION=1.27.3 --tag registry.example.com/team/web:1.27.3 --file deploy/Dockerfile ." }""") print(yaml.safe_dump(data, sort_keys=False)) print(yaml.safe_dump(data, sort_keys=False, width=4096, allow_unicode=True)) owner: "Zo\xEB M\xFCller" run: docker build --pull --build-arg VERSION=1.27.3 --tag registry.example.com/team/web:1.27.3 --file deploy/Dockerfile . owner: Zoë Müller run: docker build --pull --build-arg VERSION=1.27.3 --tag registry.example.com/team/web:1.27.3 --file deploy/Dockerfile . A folded command is valid YAML, but you can no longer grep for it.
3. PyYAML indents lists flush with the key, and one override fixes the diff noise
By default a list prints as ports: followed by - 80 at the same indent as ports. It is valid YAML, but many hand-written Kubernetes and Actions files indent list items under the key, so every list in a generated file shows up as a changed line in your diff.
Override increase_indent on a SafeDumper subclass and lists indent like the files you already have. The subclass leaves yaml.SafeDumper itself untouched.
import json import yaml class IndentDumper(yaml.SafeDumper): def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) data = json.loads('{"name": "web", "ports": [80, 443], "args": ["--port", "80"]}') print(yaml.safe_dump(data, sort_keys=False)) print(yaml.dump(data, Dumper=IndentDumper, sort_keys=False)) name: web ports: - 80 - 443 args: - --port - '80' name: web ports: - 80 - 443 args: - --port - '80' 4. Strip the quotes PyYAML adds and no becomes False
Dumping strings that look like other types is safe, because safe_dump adds quotes. The damage happens when someone removes them. Before you tidy quotes out of a generated file, check for values like no, on, off and leading-zero numbers.
PyYAML follows YAML 1.1, where yes, no, on, off, true and false are booleans. A number like 0123 is read as octal, which is 83. A JSON string "no" is just a string, so PyYAML writes it with quotes to keep it that way.
This also answers the "json to yaml no quotes" question. The quotes around 'false' are PyYAML preserving the type. Strip them and your string becomes a boolean.
This is the case that bites: a country-code table or a feature-flag file where a teammate removes the quotes because they look redundant. The block below dumps, checks the round trip, then does exactly that cleanup:
import json import yaml data = json.loads('{"country": "no", "zip": "0123", "debug": false}') text = yaml.safe_dump(data, sort_keys=False) print(text) print(yaml.safe_load(text) == data) tidied = text.replace("'", "") print(tidied) print(yaml.safe_load(tidied)) country: 'no' zip: '0123' debug: false True country: no zip: 0123 debug: false {'country': False, 'zip': 83, 'debug': False} Try this: run
python -c "import yaml; print(yaml.safe_load('country: no'))"and see what comes back. Then grep your own YAML files for unquotedno,onandoffvalues, especially country codes and feature flags.
5. Multiline strings need a literal-block representer
By default, a string with newlines prints as a single-quoted scalar that spans several lines, with a blank line for every newline in the original. It is correct, and hard to read. A small representer on a SafeDumper subclass turns those strings into | blocks, which is how CI scripts should look.
The representer picks the literal style whenever a string contains a newline. It applies to every string in the dump, so keep it on a subclass. The block header is | when the string ends with a newline and |- when it does not, and the data below has one of each.
PyYAML decides whether a literal block is safe for each string. When it is not (trailing spaces on a line are one case), it falls back to a quoted string, so check the diff on real data.
import json import yaml class Dumper(yaml.SafeDumper): pass def str_presenter(dumper, text): style = "|" if "\n" in text else None return dumper.represent_scalar("tag:yaml.org,2002:str", text, style=style) Dumper.add_representer(str, str_presenter) data = json.loads( '{"steps": [{"name": "Test", "run": "npm ci\\nnpm test\\nnpm run build\\n"},' ' {"name": "Lint", "run": "npm run lint\\nnpm run typecheck"}]}' ) print(yaml.safe_dump(data, sort_keys=False)) print(yaml.dump(data, Dumper=Dumper, sort_keys=False)) steps: - name: Test run: 'npm ci npm test npm run build ' - name: Lint run: 'npm run lint npm run typecheck' steps: - name: Test run: | npm ci npm test npm run build - name: Lint run: |- npm run lint npm run typecheck 6. YAML to JSON: duplicate keys win silently, aliases expand, comments vanish
yaml.safe_load plus json.dumps converts YAML to JSON. If a mapping has the same key twice, PyYAML keeps the last one and says nothing.
That is how replicas: 2 becomes replicas: 5 after somebody pastes a block twice. A loader subclass that checks keys before building the mapping catches it, and it is still a SafeLoader, so it is as safe as the original.
Anchors and aliases have no JSON equivalent, so <<: *defaults is expanded into plain copies of the values. Comments are dropped too, and if you need to edit YAML and keep them, ruamel.yaml round-trips comments where PyYAML cannot.
import json import yaml class UniqueKeyLoader(yaml.SafeLoader): def construct_mapping(self, node, deep=False): seen = set() for key_node, _ in node.value: if key_node.tag == "tag:yaml.org,2002:merge": continue # merge keys are expanded by flatten_mapping key = self.construct_object(key_node, deep=deep) if key in seen: raise yaml.constructor.ConstructorError( None, None, f"duplicate key: {key!r}", key_node.start_mark ) seen.add(key) return super().construct_mapping(node, deep=deep) aliases = """\ defaults: &defaults retries: 3 timeout: 30 service: <<: *defaults timeout: 60 """ print(json.dumps(yaml.load(aliases, Loader=UniqueKeyLoader), indent=2)) dup = "replicas: 2\nreplicas: 5\n" print(json.dumps(yaml.safe_load(dup))) try: yaml.load(dup, Loader=UniqueKeyLoader) except yaml.YAMLError as err: print(err) { "defaults": { "retries": 3, "timeout": 30 }, "service": { "retries": 3, "timeout": 60 } } {"replicas": 5} duplicate key: 'replicas' in "<unicode string>", line 2, column 1: replicas: 5 ^ Try this: swap
UniqueKeyLoaderinto whatever script reads your real manifests or workflow files and see whether it errors.
7. Two YAML inputs crash the conversion: --- files and unquoted dates
Duplicate keys fail quietly. These two fail loudly, which is the better kind. safe_load raises on a multi-document file, and json.dumps raises on an unquoted date.
Kubernetes manifests often hold several resources in one file, split by a --- line at column 0. safe_load refuses that input. safe_load_all returns a generator, so wrap it in list() to get a JSON array, and send the documents back out with safe_dump_all:
import json import yaml text = """\ apiVersion: v1 kind: ConfigMap metadata: name: web-config --- apiVersion: v1 kind: Service metadata: name: web """ try: yaml.safe_load(text) except yaml.YAMLError as err: print(err) docs = list(yaml.safe_load_all(text)) print(json.dumps(docs)) print(yaml.safe_dump_all(docs, sort_keys=False)) expected a single document in the stream in "<unicode string>", line 1, column 1: apiVersion: v1 ^ but found another document in "<unicode string>", line 5, column 1: --- ^ [{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "web-config"}}, {"apiVersion": "v1", "kind": "Service", "metadata": {"name": "web"}}] apiVersion: v1 kind: ConfigMap metadata: name: web-config --- apiVersion: v1 kind: Service metadata: name: web Dates trip a different wire. safe_load turns 2026-10-15 into a datetime.date, which JSON has no type for. Quote the date in the YAML, or pass default=str to json.dumps:
import json import yaml loaded = yaml.safe_load("released: 2026-10-15") print(loaded) try: json.dumps(loaded) except TypeError as err: print(err) print(json.dumps(loaded, default=str)) {'released': datetime.date(2026, 10, 15)} Object of type date is not JSON serializable {"released": "2026-10-15"} 8. Bundle it once: a json_to_yaml helper you can paste into a repo
My default call is sort_keys=False, width=4096 and allow_unicode=True, plus the indent and literal-block fixes from recipes 3 and 5. Put all of it behind one function so nobody on the team has to remember the arguments.
Open and write files with an explicit encoding="utf-8". With allow_unicode=True the output contains real non-ASCII characters, and a platform default encoding can mangle them. The demo writes its own input file so you can run it as is:
import json from pathlib import Path import yaml class _Dumper(yaml.SafeDumper): def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def _str_presenter(dumper, text): style = "|" if "\n" in text else None return dumper.represent_scalar("tag:yaml.org,2002:str", text, style=style) _Dumper.add_representer(str, _str_presenter) def json_to_yaml(raw: str) -> str: return yaml.dump( json.loads(raw), Dumper=_Dumper, sort_keys=False, width=4096, allow_unicode=True, ) Path("config.json").write_text( '{"name": "web", "owner": "Zo\\u00eb", "run": "npm ci\\nnpm test\\n",' ' "ports": [80, 443], "country": "no"}', encoding="utf-8", ) yaml_text = json_to_yaml(Path("config.json").read_text(encoding="utf-8")) Path("config.yaml").write_text(yaml_text, encoding="utf-8") print(yaml_text) name: web owner: Zoë run: | npm ci npm test ports: - 80 - 443 country: 'no' Run on Python 3.12.16, PyYAML 6.0.3. The quoted 'no' in the output is the helper doing its job, so leave it alone.
No-code option
For a one-off conversion where you do not want to open a REPL, there is a browser alternative with the same quoting rules where nothing is uploaded.
