JavaScript Object Notation commonly known as JSON, is a convenient format for many reasons and it is no wonder that many APIs and web services today support returning (in some cases exclusively) JSON. Many times I have had a need to parse values from large JSON Objects in a shell script environment or a command line shell, and use them as inputs to another program. This has put me on the look out for easy ways to handle inline parsing of JSON Objects using languages commonly available on modern Linux systems.
Below are examples in three languages (Node JS, Python and Perl) to accomplish this task.
Example JSON Object:
{"product": {"builds": {"1234": "IT WORKS!"}, "default": "1234"}}
Inline Node JS:
node -e "s=''; i=process.stdin; i.on('data', function(d) { s += d }); i.on('end', function() { j=JSON.parse(s).product; console.log(j.builds[j.default]) })"
Inline Python:
python -c 'import sys, json; j=json.load(sys.stdin)["product"]; print j["builds"][j["default"]]'
Inline Perl:
perl -e 'use JSON; local $/; $d=decode_json(<>)->{product}; print $d->{builds}->{$d->{default}}'
- The JSON module is required in the above example. If not already available it can easily be installed via CPAN with:
sudo perl -MCPAN -e 'install JSON'
Full example for Python:
echo '{"product": {"builds": {"1234": "IT WORKS!"}, "default": "1234"}}' |python -c 'import sys, json; j=json.load(sys.stdin)["product"]; print j["builds"][j["default"]]'