rzlvmp
rzlvmp

Reputation: 9364

How to convert json to yaml and vice versa in command line?

How convert JSON file into YAML and vice versa in command line?

Any ways are welcome.

Upvotes: 22

Views: 22045

Answers (4)

goulashsoup
goulashsoup

Reputation: 3076

As it turns out, there are two different yq commands, see Executing yq, but jq gets executed, so for anyone installing yq on a Debian based Linux you will end up with kislyuk/yq which works differently then most upvoted mikefarah/yq:

yq --help
  # yq: Command-line YAML processor - jq wrapper for YAML documents
  # yq transcodes YAML documents to JSON and passes them to jq.
  # See https://github.com/kislyuk/yq for more information.

Transform YAML to JSON with kislyuk/yq:

cat in.yaml | yq . > out.json

Transform JSON to YAML with kislyuk/yq:

yq -y . < in.json > out.yaml

Upvotes: 2

Jajikanth pydimarla
Jajikanth pydimarla

Reputation: 1572

Below code help to convert yml to json after installing yq

version 4.44.2

yq -o=json your_file.yml > your_file.json

Upvotes: 0

pbatey
pbatey

Reputation: 1433

Update: as of yq version 4.18:

The flags -p and -o let you specify input and output formats. You can convert between yaml, json, and xml!

yq -p json -o yaml file.json # json -> yaml
yq -p json -o xml file.json  # json -> xml
yq -p yaml -o json file.yaml # yaml -> json
yq -p yaml -o xml file.yaml  # yaml -> xml
yq -p xml -o json file.xml   # xml -> json
yq -p xml -o yaml file.xml   # xml -> yaml

With yq version 4.8.0:

yq e -P file.json yields YAML

yq e -j file.yaml yields JSON

  • e or eval evaluates each file separately. ea or eval-all merges them first.
  • -P or --prettyPrint outputs YAML
  • -j or --tojson outputs JSON

Upvotes: 48

rzlvmp
rzlvmp

Reputation: 9364

My python way:

  1. create file yjconverter
#!/usr/bin/env python

import json,yaml,sys,os

if len(sys.argv) != 2:
  print('Usage:\n  '+os.path.basename(__file__)+' /path/file{.json|.yml}')
  sys.exit(0)

path = sys.argv[1]

if not os.path.isfile(path):
  print('Bad or non-existant file: '+path)
  sys.exit(1)

with open(path) as file:

  if path.lower().endswith('json'):
    print(yaml.dump(json.load(file), Dumper=yaml.CDumper))
  elif path.lower().endswith('yaml') or path.lower().endswith('yml'):
    print(json.dumps(yaml.load(file, Loader=yaml.SafeLoader), indent=2))
  else:
    print('Bad file extension. Must be yml or json')
  1. add execution permissions and move file into bin:
chmod +x yjconverter
sudo mv yjconverter /usr/local/bin/
  1. run yjconverter some_file.json or yjconverter some_file.yml

  2. profit

Upvotes: 6

Related Questions