Skip to content

Instantly share code, notes, and snippets.

@iwill
Last active October 12, 2015 15:28
Show Gist options
  • Save iwill/4047683 to your computer and use it in GitHub Desktop.
Save iwill/4047683 to your computer and use it in GitHub Desktop.
JSON Parsing and Editing, run Javascript Function and Statements in Shell via Node.js
#!/bin/bash
# @see https://www.npmjs.org/package/json
## nodejs [js-statement ...] js-expression
function nodejs() {
local statements=""
while [[ $# > 1 ]]; do
statements="${statements:+$statements; }$1"
shift
done
node -e "${statements}; var __nodejs_result__ = $1; console.log(__nodejs_result__);"
}
export -f nodejs
## nodejs js-expression
# @see http://stackoverflow.com/questions/23500098/node-js-syntaxerror-unexpected-end-of-input
# nodejs() {
# node -e "console.log($1)"
# }
@iwill
Copy link
Author

iwill commented Apr 9, 2013

Parse JSON

Parse JSON Object

> object='{ "name": "iwill", "pet": "zozo" }'
> nodejs "$object.name"
# iwill

Parse JSON Array

> array='[ "iwill", "zozo" ]'
> nodejs "$array[0]"
# iwill

JS Function

Call JS Function

> add="function(a, b) { return a + b; }"
> nodejs "$add(1, 2)"
#3

Edit JSON via JS Function

> object='{ "name": "iwill", "pet": "zozo" }'
> modify="function(object, name, value) { object[name] = value; return JSON.stringify(object); }"
> nodejs "$modify($object, 'name', 'wills')"
# {"name":"wills","pet":"zozo"}

JS Statements

Call JS Statements + Expression

> nodejs "var a = 1; var b = 2;" "a + b"
#3

Edit JSON via JS Statements + Expression

> object="{ 'name': 'iwill', 'pet': 'zozo' }"
> nodejs "var object = $object; object.name = 'wills';" "object"
# {"name":"wills","pet":"zozo"}

???: Edit JSON via JS Statements + Return

> object="{ 'name': 'iwill', 'pet': 'zozo' }"
> nodejs "var object = $object; object.name = 'wills'; return object;"
# {"name":"wills","pet":"zozo"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment