DEV Community

arenasbob2024-cell
arenasbob2024-cell

Posted on • Originally published at viadreams.cc

JSON vs YAML: When to Use Each and How to Convert

JSON and YAML both represent structured data, but they serve different ecosystems. Here is when to use each and how to convert between them.

Side-by-Side

JSON:

{
  "server": {
    "host": "0.0.0.0",
    "port": 3000,
    "features": ["cors", "compression"]
  }
}
Enter fullscreen mode Exit fullscreen mode

YAML:

server:
  host: "0.0.0.0"
  port: 3000
  features:
    - cors
    - compression
Enter fullscreen mode Exit fullscreen mode

When to Use Each

Use Case JSON YAML
API responses Yes No
Kubernetes configs No Yes
Docker Compose No Yes
package.json Yes No
CI/CD pipelines No Yes

YAML Gotchas

The Norway Problem

norway: NO    # Boolean false, not string 'NO'!
country: "NO" # String 'NO'
Enter fullscreen mode Exit fullscreen mode

Type Coercion

version: 1.0     # float, not string
phone: 0123456   # octal number!
time: 12:30      # sexagesimal (750)
Enter fullscreen mode Exit fullscreen mode

Fix: Always quote values that should be strings.

Security Warning

# NEVER do this!
yaml.load(user_data)  # Can execute code!

# ALWAYS use safe_load
yaml.safe_load(user_data)
Enter fullscreen mode Exit fullscreen mode

Try It Online

Convert JSON to YAML with DevToolBox Converter - bidirectional, syntax highlighting.


JSON or YAML for configs? Comment below!

Top comments (0)