Conversions entre JSON & YAML
Mis à jour le 24/10/2023

Remarques

JSON vers YAML

En CLI (idéalement Unix mais souvent utilisable sous Windows), selon les outils installés
source: https://lzone.de/blog/Convert-JSON-to-YAML-in-Linux-bash

Dans l’ordre de mes préférences:

Python

python -c 'import sys, yaml, json; print(yaml.dump(json.loads(sys.stdin.read())))' <input.json

yq

yq -oy input.json

jq

Place the following into ~/.jq

def yamlify2:
    (objects | to_entries | (map(.key | length) | max + 2) as $w |
        .[] | (.value | type) as $type |
        if $type == "array" then
            "\(.key):", (.value | yamlify2)
        elif $type == "object" then
            "\(.key):", "    \(.value | yamlify2)"
        else
            "\(.key):\(" " * (.key | $w - length))\(.value)"
        end
    )
    // (arrays | select(length > 0)[] | [yamlify2] |
        "  - \(.[0])", "    \(.[1:][])"
    )
    // .
    ;

And convert using:

jq -r yamlify2 input.json

Ruby

ruby -ryaml -rjson -e 'puts YAML.dump(JSON.parse(STDIN.read))' <input.json

Perl

perl -MYAML -MJSON -0777 -wnl -e 'print YAML::Dump(decode_json($_))' input.json

YAML vers JSON

JSON sur une seule ligne

cat input.json |jq -c


En CLI (idéalement Unix mais souvent utilisable sous Windows), selon les outils installés

Dans l’ordre de mes préférences:

Python

python -c 'import sys, yaml, json; print(json.dumps(yaml.load(sys.stdin.read(),Loader=yaml.FullLoader)))' <input.yaml

Pour du prettyJSON

python -c 'import sys, yaml, json; print(json.dumps(yaml.load(sys.stdin.read(),Loader=yaml.FullLoader),indent=2))' <input.yaml

ou

python -c 'import sys, yaml, json; print(json.dumps(yaml.load(sys.stdin.read(),Loader=yaml.FullLoader)))' <input.yaml | jq

yq

yq -oj input.yaml

Ruby

ruby -ryaml -rjson -e 'puts JSON.pretty_generate(YAML.load(ARGF))' <input.yaml

Commande ansible vers YAML

Ici, on va utiliser yq pour sa simplicité, plutôt que les autres méthodes de conversion JSON vers YAML expliquées dans cet article.
Car le 1er objectif est de transformer la sortie d’une commande ad-hoc ansible en JSON.

La commande sed qui transforme la sortie d’une commande ad-hoc ansible en JSON, en créant une clef hostname (pour ne pas perdre cette information):

sed -E -e 's/(.+) \| .+ => \{$/\{ "hostname": "\1",/' \
       -e '1 i \[' -e 's/^\}$/\},/' -e '$ c \}' |sed '$ a \]'

Donc, on l’utilise par exemple comme ceci:

ansible all -m ping | \
sed -E -e 's/(.+) \| .+ => \{$/\{ "hostname": "\1",/' \
       -e '1 i \[' -e 's/^\}$/\},/' -e '$ c \}' |sed '$ a \]' | \
yq -oy -pj

Et on obtient cette sortie:

- hostname: 10.146.237.207
  ansible_facts:
    discovered_interpreter_python: /usr/bin/python3
  changed: false
  ping: pong
- hostname: 10.146.237.111
  ansible_facts:
    discovered_interpreter_python: /usr/bin/python3
  changed: false
  ping: pong

results matching ""

    No results matching ""