Code golf!
"import sys, json; data=json.loads(sys.stdin.read()); print data.get('$1') or ''"
Pregunta
I am very new to python and am trying to use it to parse a file with JSON in it within my bash_profile script, and return the value. I can't seem to get the if statement working. It will read the contents of the file, but I recieve this error, with an arrow under the if statement.
File "<string>", line 1
import sys,json;data=json.loads(sys.stdin.read());if data['123456789']:print...
^
SyntaxError: invalid syntax
Contents of File:
{"123456789":"Well Hello"}
Function that searches file:
function find_it {
file=~/.pt_branches
CURRENT_CONTENTS=`cat $file`
echo $CURRENT_CONTENTS | python -c "import sys,json;data=json.loads(sys.stdin.read());if data['$1']:print data['$1'];else:print '';"
}
Command
find_it "123456789"
If I were to remove the if statement and just return the value, it does work, but I want it to be able to return and empty string if it does not exist.
echo $CURRENT_CONTENTS | python -c "import sys,json;data=json.loads(sys.stdin.read());print data['$1'];"
Any ideas on what I am doing wrong?!?
Solución
Code golf!
"import sys, json; data=json.loads(sys.stdin.read()); print data.get('$1') or ''"
Otros consejos
Do this:
echo $CURRENT_CONTENTS | python -c "
import sys
import json
data = json.loads(sys.stdin.read())
if data['$1']:
print data['$1']
else:
print ''"