How convert JSON file into YAML and vice versa in command line?
Any ways are welcome.
2 Answers
With yq version 4.8.0:
yq e -P file.json yields YAML
yq e -j file.yaml yields JSON
eorevalevaluates each file separately.eaoreval-allmerges them first.-Por--prettyPrintoutputs YAML-jor--tojsonoutputs JSON
My python way:
- 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') - add execution permissions and move file into bin:
chmod +x yjconverter sudo mv yjconverter /usr/local/bin/ run
yjconverter some_file.jsonoryjconverter some_file.ymlprofit