4
input = json.load(sys.stdin)
print(input['id'])

When I input {"id":1} and hit enter, my program does not continue, I am just stuck typing in my input. How can I make the program continue after valid json has been passed to my stdlin?

4
  • You have to close the file. On Linux and other Unix-like systems you do that by hitting Ctrl-D. I think on Windows you need Ctrl-Z, but I don't know much about Windows. Commented May 4, 2018 at 17:58
  • BTW, you forgot to include the import statements in your code. And don't use input as a variable name, that shadows the built-in input function. Commented May 4, 2018 at 17:59
  • To be perfectly clear - this is a BUG in the python library. Its perfectly clear when the end of a JSON object is parsing (only one character lookahead needed). Some JSON parsing libraries (c++) do this correctly, and so the above usage - reading from stdin - would work just fine; this reader <github.com/SophistSolutions/Stroika/blob/v2.1b9/Library/Sources/…> only looks ahead one character at most to find end of JSON. Commented Jan 18, 2021 at 17:02
  • 1
    This is not a bug. json.load takes an open file and reads its whole contents, and the documentation states that it uses read() to do so. Commented Feb 5, 2021 at 18:49

2 Answers 2

4

when you read in from sys.stdin it will read everything until it hits an EOF character normally ctrl-d so if you input {"id":1} <ENTER> ctrl-d it should work.

It looks like what you are trying to do is something like this

import json
json_as_str = input()
json_obj = json.loads(json_as_str)
print(json_obj['id'])
Sign up to request clarification or add additional context in comments.

Comments

1

I tried the code interactively by pasting the two lines in and then realised the second line was being interpreted as part of the JSON the first line was reading! As a module the code works perfectly predictably. The visible input was followed by a newline and CTRL/D on the console.

sholden$ cat /tmp/py.py
import json, sys
input = json.load(sys.stdin)
print(input['id'])
sholden$ python /tmp/py.py
{"id": 42}
42

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.