Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Created July 31, 2013 09:59
Show Gist options
  • Select an option

  • Save coderofsalvation/6120853 to your computer and use it in GitHub Desktop.

Select an option

Save coderofsalvation/6120853 to your computer and use it in GitHub Desktop.
Simple way to get JSON variables in bash using PHP. Works on probably on all webservers (with php installed)
#!/bin/bash
#
# example usage : xpath /tmp/test.json "foo->flop"
# example output: XML Developer's Guide
#
# given that /tmp/test.json looks like:
# { "foo": { "flop": "bar" } }
phpcode_jsonget='
$parts = str_replace( array("'"'"'","]"), "", $argv[2] );
$parts = explode( "->", $parts );
$data = file_get_contents($argv[1]);
$data = str_replace("\n","", $data); // indented json breaks json_decode()
$data = json_decode( $data );
foreach( $parts as $part )
if( isset( $data->$part ) ) $data = $data->$part;
echo ( is_string($data) ) ? $data : "";
'
# getJSON jsonfile query
getJSON(){
php -r "$phpcode_jsonget" "$1" "$2"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment