如何将多行JSON字符串作为参数传入Python脚本?
When you need to feed a nicely formatted, multi-line JSON into a Python script, there are several practical approaches depending on your use case and shell environment. Here are the most reliable methods to get the job done:
1. Read JSON from Standard Input (stdin)
This is a clean, pipe-friendly approach—perfect if you want to either write the JSON inline or pipe it from an existing source.
Python Script Example (script.py):
import sys import json def main(): try: # Read and parse JSON directly from stdin data = json.load(sys.stdin) print("Successfully parsed JSON:") print(json.dumps(data, indent=2)) except json.JSONDecodeError as e: print(f"Oops, invalid JSON: {e}") if __name__ == "__main__": main()
Running the Script:
Using a Here-Document (Bash/Zsh):
Write your JSON directly in the command line without a separate file:
python script.py << EOF { "name": "Alice", "age": 30, "hobbies": ["reading", "hiking", "coding"], "address": { "street": "123 Main St", "city": "Anytown" } } EOF
Piping from a File:
If your JSON is already saved to a file (like data.json), pipe it into the script:
cat data.json | python script.py
2. Pass JSON as a Quoted Command-Line Argument
For small JSON snippets, you can wrap the multi-line JSON in quotes and pass it as a positional argument. Just be mindful of shell escaping rules.
Python Script Example (script.py):
import sys import json def main(): if len(sys.argv) < 2: print("Usage: python script.py '<your-JSON>'") return try: data = json.loads(sys.argv[1]) print("Successfully parsed JSON:") print(json.dumps(data, indent=2)) except json.JSONDecodeError as e: print(f"Invalid JSON: {e}") if __name__ == "__main__": main()
Running the Script:
In Bash/Zsh:
Use single quotes to preserve line breaks and formatting (avoid single quotes inside your JSON, or escape them with '\''):
python script.py '{ "name": "Bob", "age": 25, "is_student": true }'
In PowerShell:
Use a here-string for clean multi-line input:
python script.py @" { "name": "Charlie", "age": 35, "email": "charlie@example.com" } "@
Note: This method works best for short JSON. For large or complex structures, stick to the file method below to avoid escaping headaches.
3. Read JSON from a File (Most Reliable for Large JSON)
Storing your formatted JSON in a separate file and passing the file path as an argument is the most straightforward and error-proof method, especially for big datasets.
Python Script Example (script.py):
import sys import json def main(): if len(sys.argv) < 2: print("Usage: python script.py <path-to-json-file>") return file_path = sys.argv[1] try: with open(file_path, 'r') as f: data = json.load(f) print("Successfully parsed JSON:") print(json.dumps(data, indent=2)) except FileNotFoundError: print(f"Error: File '{file_path}' doesn't exist.") except json.JSONDecodeError as e: print(f"Invalid JSON in file: {e}") if __name__ == "__main__": main()
Running the Script:
Save your JSON to data.json:
{ "products": [ {"id": 1, "name": "Laptop", "price": 999.99}, {"id": 2, "name": "Phone", "price": 699.99} ], "store": "TechMart" }
Then run:
python script.py data.json
4. Pass JSON via Environment Variable
If you need to pass JSON alongside other command-line arguments, storing it in an environment variable is a handy option.
Python Script Example (script.py):
import os import json def main(): json_data = os.environ.get('MY_JSON') if not json_data: print("Error: Set the MY_JSON environment variable first.") return try: data = json.loads(json_data) print("Successfully parsed JSON:") print(json.dumps(data, indent=2)) except json.JSONDecodeError as e: print(f"Invalid JSON: {e}") if __name__ == "__main__": main()
Running the Script (Bash/Zsh):
Export the JSON as an environment variable (use single quotes to keep formatting intact):
export MY_JSON='{ "user": "dave", "permissions": ["read", "write"], "active": true }' python script.py
内容的提问来源于stack exchange,提问作者Abdul Jaleel

