Python调用YouTube API v3的JSON终端输出无格式,求格式化方案
Command-Line Quick Fixes
These are the easiest ways to format your unstructured JSON directly in the terminal without modifying your code:
1. Use Python's Built-in json.tool
Python comes with a native JSON formatter that requires no extra installation. If you're using curl to call the API, pipe the output to this tool:
curl "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=YOUR_PLAYLIST_ID&key=YOUR_API_KEY" | python -m json.tool
If you already have the JSON stored in a shell variable, do this instead:
echo "$YOUR_JSON_RESPONSE" | python -m json.tool
2. Use jq (Powerful JSON Processor)
jq is a dedicated command-line tool for JSON manipulation and formatting—it’s fast and adds color coding for readability. First install it:
- Debian/Ubuntu:
sudo apt-get install jq - macOS:
brew install jq - Windows: Use Chocolatey (
choco install jq) or download from the official repository
Once installed, pipe your API response to jq:
curl "YOUR_YOUTUBE_API_ENDPOINT" | jq
Just jq alone will format the entire output with proper indentation. You can also use jq '.' to explicitly target the full JSON structure if needed.
3. Use Node.js (If Already Installed)
If you have Node.js set up, leverage its built-in JSON handling:
curl "YOUR_YOUTUBE_API_ENDPOINT" | node -e "const data = JSON.parse(require('fs').readFileSync(0, 'utf8')); console.log(JSON.stringify(data, null, 2))"
Or a shorter version:
curl "YOUR_YOUTUBE_API_ENDPOINT" | node -p "JSON.stringify(JSON.parse(require('fs').readFileSync(0)), null, 2)"
Code-Based Solutions (For Scripts)
If you’re making the API call via a programming language, format the JSON directly in your code before printing:
Python Example
import requests import json api_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=YOUR_PLAYLIST_ID&key=YOUR_API_KEY" response = requests.get(api_url) # Format with 2-space indentation formatted_json = json.dumps(response.json(), indent=2) print(formatted_json)
JavaScript (Node.js) Example
const fetch = require('node-fetch'); async function fetchFormattedYoutubeData() { const apiUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=YOUR_PLAYLIST_ID&key=YOUR_API_KEY"; const response = await fetch(apiUrl); const data = await response.json(); // Format with 2-space indentation console.log(JSON.stringify(data, null, 2)); } fetchFormattedYoutubeData();
Any of these methods will turn your single-line JSON blob into a clean, structured output that’s easy to read in the terminal.
内容的提问来源于stack exchange,提问作者ManuellsenDeve

