Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
283 changes: 227 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,76 +1,247 @@
# json2yaml
# yaml-json-cli

Command line utilities to convert between JSON and YAML while
preserving the order of associative arrays.
Bidirectional **YAML ↔ JSON** converter for the command line and Python API.

Preserving the mapping order is helpful to humans reading the
documents, despite not affecting their meaning.
```
yaml-json-cli config.yaml -o config.json
yaml-json-cli data.json -o data.yaml
```

## Install
---

```pip install json2yaml```
## Features

## Usage
```json2yaml input.json output.yaml```
- **YAML → JSON** — full nested-structure preservation, multi-document support
- **JSON → YAML** — block (default) or flow style output
- **Multi-document YAML** (`---` separators) → JSON array
- **YAML anchors & aliases** resolved automatically
- **Date/datetime** values serialized to ISO-8601 strings
- **stdin/stdout** pipeline support
- Configurable indent, sort-keys, encoding
- Zero mandatory dependencies beyond **PyYAML**

```yaml2json input.yaml output.json```
---

## Installation

```bash
pip install yaml-json-cli
```
$ json2yaml --help
Usage:
json2yaml (--version|--help)
json2yaml [<json_file>] [<yaml_file>]

Arguments:
<json_file> The input file containing the JSON to convert. If not
specified, reads from stdin.
<yaml_file> The output file to which to write the converted YAML. If
not specified, writes to stdout.

Or from source:

```bash
git clone https://github.com/toxfox69/yaml-json-cli
cd yaml-json-cli
pip install .
```

---

## CLI Usage

```
$ yaml2json --help
Usage:
yaml2json (--version|--help)
yaml2json [-i <indent>] [<yaml_file>] [<json_file>]

Arguments:
-i, --indent=INDENT Number of spaces to indent [default: 4]
<yaml_file> The input file containing the YAML to convert. If not
specified, reads from stdin.
<json_file> The output file to which to write the converted JSON.
If not specified, writes to stdout.
yaml-json-cli INPUT [-o OUTPUT] [options]

positional arguments:
INPUT Input file (.yaml, .yml, or .json)

options:
-o, --output Output file (default: stdout)
--from FORMAT Force input format: yaml or json
--indent N JSON indent width (default: 2)
--sort-keys Sort mapping keys in output
--flow-style Compact YAML flow style (JSON-like)
--encoding ENC File encoding (default: utf-8)
--version Show version and exit
-h, --help Show help message
```

## Changelog
### Examples

+ 1.2.0 (October 19, 2021)
+ support Python 3
+ support multiple yaml documents in one file
+ learn to wrap multiple yaml documents in a JSON array (-a | --array)
+ use yaml safe_load to prevent loading of arbitrary Python objects
+ 1.1.1 (March 16, 2015)
+ terminate json output with newline
+ 1.1.0 (March 16, 2015)
+ take indent as command line argument (-i | --indent)
+ prevent trailing spaces in json output
```bash
# YAML → JSON (print to stdout)
yaml-json-cli config.yaml

## Authors
**David Bild**
# YAML → JSON (write to file)
yaml-json-cli config.yaml -o config.json

+ [https://www.davidbild.org](https://www.davidbild.org)
+ [https://github.com/drbild](https://github.com/drbild)
# JSON → YAML (write to file)
yaml-json-cli data.json -o data.yaml

## License
Copyright 2015 David R. Bild
# JSON → YAML (print to stdout)
yaml-json-cli data.json

# Sort keys in output
yaml-json-cli config.yaml --sort-keys -o config.json

# 4-space JSON indent
yaml-json-cli config.yaml --indent 4 -o config.json

# Compact YAML flow style
yaml-json-cli data.json --flow-style

# Multi-document YAML → JSON array
yaml-json-cli multi.yaml -o out.json

# Force format (useful for stdin or non-standard extensions)
cat config.yaml | yaml-json-cli /dev/stdin --from yaml

# Force JSON input from a .txt file
yaml-json-cli data.txt --from json -o data.yaml
```

---

## Input / Output Examples

### YAML → JSON

**Input** (`config.yaml`):
```yaml
server:
host: localhost
port: 8080
database:
url: postgres://localhost/mydb
pool_size: 10
features:
- auth
- logging
- metrics
debug: false
```

**Output** (`config.json`):
```json
{
"server": {
"host": "localhost",
"port": 8080
},
"database": {
"url": "postgres://localhost/mydb",
"pool_size": 10
},
"features": [
"auth",
"logging",
"metrics"
],
"debug": false
}
```

---

### JSON → YAML

**Input** (`data.json`):
```json
{
"users": [
{"id": 1, "name": "Alice", "active": true},
{"id": 2, "name": "Bob", "active": false}
]
}
```

**Output** (`data.yaml`):
```yaml
users:
- active: true
id: 1
name: Alice
- active: false
id: 2
name: Bob
```

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License from the LICENSE.txt file or at
---

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
### Multi-document YAML → JSON array

**Input** (`services.yaml`):
```yaml
name: api
port: 8080
---
name: worker
port: 9090
```

**Output**:
```json
[
{"name": "api", "port": 8080},
{"name": "worker", "port": 9090}
]
```

---

## Python API

```python
from yaml_json_converter import yaml_to_json, json_to_yaml

# YAML file → JSON file
data = yaml_to_json("config.yaml", "config.json")

# JSON file → YAML file
data = json_to_yaml("data.json", "data.yaml", sort_keys=True)

# From string (no file I/O)
data = yaml_to_json(text="key: value\n")
data = json_to_yaml(text='{"key": "value"}')

# Options
yaml_to_json(
"input.yaml",
"output.json",
indent=4,
sort_keys=True,
encoding="utf-8",
)

json_to_yaml(
"input.json",
"output.yaml",
sort_keys=False,
default_flow_style=False,
encoding="utf-8",
)
```

---

## Error Handling

The CLI exits with:

| Code | Meaning |
|------|---------|
| `0` | Success |
| `1` | File not found or parse error (message printed to stderr) |
| `2` | Bad arguments (argparse) |
| `130`| Interrupted (Ctrl-C) |

The library raises:
- `FileNotFoundError` — input file missing
- `ValueError` — malformed YAML or JSON, empty document

---

## Development

```bash
pip install -e ".[dev]"
pytest test_converter.py -v
pytest test_converter.py -v --cov=yaml_json_converter --cov-report=term-missing
```

---

## License

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
MIT — Copyright © 2026 ENERGENAI LLC
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pyyaml>=6.0
69 changes: 44 additions & 25 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,50 @@
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools import setup

from os.path import join as pjoin
with open("README.md", encoding="utf-8") as fh:
long_description = fh.read()

setup(
name = 'json2yaml',
version = '1.2.1-SNAPSHOT',
author = 'David R. Bild',
author_email = 'david@davidbild.org',
keywords = 'yaml json converter ordered order preserving',
url = 'https://github.com/drbild/json2yaml',
description = 'Convert JSON to YAML or vice versa, while'
' preserving the order of associative arrays.',
classifiers = [
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
name="yaml-json-cli",
version="1.0.0",
author="ENERGENAI LLC",
author_email="tiamat@tiamat.live",
description="Bidirectional YAML ↔ JSON converter CLI and library",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/toxfox69/yaml-json-cli",
py_modules=["yaml_json_converter"],
python_requires=">=3.8",
install_requires=[
"pyyaml>=6.0",
],
scripts = [
pjoin('bin', 'json2yaml'),
pjoin('bin', 'yaml2json')
extras_require={
"dev": [
"pytest>=7.0",
"pytest-cov>=4.0",
]
},
entry_points={
"console_scripts": [
"yaml-json-cli=yaml_json_converter:main",
]
},
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Utilities",
"Topic :: Text Processing :: Markup",
"Environment :: Console",
],
install_requires = [
'pyyaml',
'pyaml',
'docopt'
]
keywords="yaml json converter cli data transformation",
license="MIT",
project_urls={
"Bug Tracker": "https://github.com/toxfox69/yaml-json-cli/issues",
"Source": "https://github.com/toxfox69/yaml-json-cli",
},
)
Loading