Gavriel Gavriel - 8 days ago 5
Python Question

1-liner for loop in python

I have this 1-liner:

python -c 'import json,sys;obj=json.load(sys.stdin);print json.dumps(obj.get("dependencies"), indent=0, sort_keys=True)' < package.json


And I would like to find a nice, short solution instead of repeating myself, to do the print looping over
["dependencies", "devDependencies", "peerDependencies"]
.

The trivial, but not nice solution I have now:

python -c 'import json,sys;obj=json.load(sys.stdin);print json.dumps(obj.get("dependencies"), indent=0, sort_keys=True);print json.dumps(obj.get("devDependencies"), indent=0, sort_keys=True);print json.dumps(obj.get("peerDependencies"), indent=0, sort_keys=True)' < package.json


I also tried things similar to:

python -c 'import json,sys;obj=json.load(sys.stdin);[print json.dumps(obj.get(dep), indent=0, sort_keys=True) for dep in "dependencies","devDependencies","peerDependencies"]' < package.json


UPDATE:

My goal is to get all the dependencies that have "git" in their url:

Input: package.json:

{
"foo": "bar",
"dependencies": {
"a": "git:aa",
"b": "git:bb",
"c": "cc"
},
"peerDependencies": {
"p": "git:pp"
},
"devDependencies": {
"d": "git:dd"
},
"moo": "poo"
}


Expected output:

{
"a": "git:aa",
"b": "git:bb",
"c": "cc"
} {
"p": "git:pp"
} {
"d": "git:dd"
}


In fact I don't care much about the "}"-s and "{"-s, because I'll continue the 1-liner with:
| grep 'git:'

Answer

you are looking for join:

import json,sys
obj=json.load(sys.stdin)
print ' '.join(json.dumps(obj.get(dep), indent=0, sort_keys=True) for dep in ("dependencies", "devDependencies", "peerDependencies"))
Comments