0

I'd like to pass a simple set of name/value pairs to a python script via json on the command line.

$ curl -s https://jsonplaceholder.typicode.com/posts/1 | python3.6 -c 'import sys, json; print json.load(sys.stdin)'
  File "<string>", line 1
    import sys, json; print json.load(sys.stdin)
                               ^
SyntaxError: invalid syntax
(23) Failed writing body

The json is simple:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat",
    "body": "quia et suscipit\nsuscipit..."
}

And the goal is to assign variables like:

if json.load(sys.stdin)["title"] is not None:
    post_title = json.load(sys.stdin)["title"]

How can I accomplish this correctly?

Ryan
  • 14,682
  • 32
  • 106
  • 179
  • 2
    `python3.6 -c 'print "anything"'` doesn't work. `print` is a function, not a statement, in Python 3.6. – Charles Duffy Apr 10 '18 at 15:48
  • doh! `curl -s https://jsonplaceholder.typicode.com/posts/1 | python3.6 -c 'import sys, json; print(json.load(sys.stdin)["title"])'` FTW. Thanks. – Ryan Apr 10 '18 at 15:49

1 Answers1

3

You need parenthesis surrounding the argument to print:

python3.6 -c 'import sys, json; print(json.load(sys.stdin))'
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    @DominikBrno, ...btw, you'll note this I marked this "Community Wiki" and am not getting points from it -- that's because answering this question was technically against the rules; see "Answer Well-Asked Questions" in https://stackoverflow.com/help/how-to-answer, particularly the bullet point regarding questions which "have been asked and answered many times before". – Charles Duffy Apr 10 '18 at 15:55
  • 1
    @DominikBrno, ...that said, because it's community-wiki, you're welcome to edit it if you think an example showing the working code (f/e, as done in your deleted answer) is a useful addition. – Charles Duffy Apr 10 '18 at 15:57