From d44af017b0fc26b49e4297a066f86808fecdfce4 Mon Sep 17 00:00:00 2001 From: Hari Sekhon Date: Tue, 18 Aug 2020 12:01:15 +0100 Subject: [PATCH] updated yaml2json.sh --- yaml2json.sh | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/yaml2json.sh b/yaml2json.sh index a25d6313..c41bb7fa 100755 --- a/yaml2json.sh +++ b/yaml2json.sh @@ -23,7 +23,7 @@ srcdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # shellcheck disable=SC2034,SC2154 usage_description=" -Converts YAML to JSON using either Python, Perl or Ruby (whichever is available in that order) +Converts YAML to JSON using either Perl, Ruby or Python (whichever is available in that order) YAML can be specified as a filename argument to piped to standard input " @@ -35,12 +35,8 @@ usage_args="[]" help_usage "$@" yaml2json(){ - # yaml is a 3rd party library, and in old 2.x versions so was json - only run the Python conversion if we have both libraries installed - if type -P python &>/dev/null && - python -c 'import yaml, json' &>/dev/null; then - python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin, Loader=yaml.FullLoader), sys.stdout, indent=4)' # needs 3rd party modules installed (YAML::XS, JSON::XS), so check we have both modules first - elif type -P perl &>/dev/null && + if type -P perl &>/dev/null && perl -MYAML::XS=Load -MJSON::XS=encode_json -e '' &>/dev/null; then #perl -MYAML::XS=LoadFile -MJSON::XS=encode_json -e 'for (@ARGV) { for (LoadFile($_)) { print encode_json($_),"\n" } }' perl -MYAML::XS=Load -MJSON::XS=encode_json -e '$/ = undef; print encode_json(Load()) . "\n"' @@ -49,6 +45,11 @@ yaml2json(){ # don't want variable expansion # shellcheck disable=SC2016 ruby -r yaml -r json -e 'puts YAML.load($stdin.read).to_json' + # moved to last as typical Python version change problems, breaks across environments with AttributeError: 'module' object has no attribute 'FullLoader' + # yaml is a 3rd party library, and in old 2.x versions so was json - only run the Python conversion if we have both libraries installed + elif type -P python &>/dev/null && + python -c 'import yaml, json' &>/dev/null; then + python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin, Loader=yaml.FullLoader), sys.stdout, indent=4)' # don't use yq - there are 2 completely different 'yq' which could appear in \$PATH, so this is unreliable #elif type -P yq &>/dev/null; then else