문제

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?!?

도움이 되었습니까?

해결책

Code golf!

"import sys, json; data=json.loads(sys.stdin.read()); print data.get('$1') or ''"

다른 팁

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 ''"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top