HardCoder
HardCoder

Reputation: 3036

convert yaml to json in bash using perl

I am trying to convert a yaml-string to json in bash using perl (unfortunately it has to be like this) and am having problems. It works when I write it to a temporary file and convert that but unfortunately I do not have enough perl-experience to change it to work with a bash-variable to perform identically. I need to do that because I want to convert many files quite often and always creating temporary files is slow/inefficient and in my case also a security issue.

This is the command that is working with the temporary file:

jsonfile=$(perl -MYAML::XS=LoadFile -MJSON::XS=encode_json -e 'for (@ARGV) { for (LoadFile($_)) { print encode_json($_),"\n" } }' ${tempfile} )

can I somehow change this to something along this?

jsonfile=$(echo "${yaml_string}" | perl .....)

I slightly changed the parameters and tried something like this but the output is quite different and not usable:

jsonfile=$(echo "${yaml_string}" | perl -MYAML::XS=Load -MJSON::XS=encode_json -e 'for (<>) { for (Load($_)) { print encode_json($_),"\n" } }')

Any assistance with this would be greatly appreciated.

Upvotes: 1

Views: 1588

Answers (2)

ikegami
ikegami

Reputation: 385917

Using arg:

# sh, bash
perl -MYAML::XS -MJSON::XS -e'CORE::say encode_json(Load($ARGV[0]))' -- "$yaml_string"

Using env var:

# sh, bash
yaml_string="$yaml_string" perl -MYAML::XS -MJSON::XS -e'CORE::say encode_json(Load($ENV{yaml_string}))'

# sh, bash
export yaml_string
perl -MYAML::XS -MJSON::XS -e'CORE::say encode_json(Load($ENV{yaml_string}))'

Using STDIN:

# sh, bash
printf '%s' "$yaml_string" | perl -MYAML::XS -MJSON::XS -0777e'CORE::say encode_json(Load(<>))'

# bash
perl -MYAML::XS -MJSON::XS -0777e'CORE::say encode_json(Load(<>))' <<<"$yaml_string"

# bash
perl -MYAML::XS -MJSON::XS -0777e'CORE::say encode_json(Load(<>))' <( printf '%s' "$yaml_string" )

Upvotes: 1

Shawn
Shawn

Reputation: 52439

If you're using bash as your shell, you can provide the contents of the yaml variable as a herestring instead of piping the output of echo:

perl -MYAML::XS -MJSON::XS -0777 -E 'say encode_json(Load(<>))' <<<"${yaml_string}"

The -0777 switch is a perl convention to tell <>/readline to read all of its input as a single value instead of as a line at a time.

Upvotes: 2

Related Questions