如何仅使用Shell脚本将指定JSON文件转换为JSON对象?
Hey there! Let's get your JSON sorted out. You've got a JSON file with extra whitespace in the values, and you want to turn it into a clean, parseable JSON object using shell tools. Here are two reliable, foolproof methods to do this:
Method 1: Use jq (The Go-To JSON Tool)
jq is the standard tool for manipulating JSON in the shell—it's built specifically for this job, so it won't break your JSON structure even if there are edge cases like special characters in strings.
Step 1: Install jq (if you don't have it)
On Debian/Ubuntu:
sudo apt install jq
On RHEL/CentOS:
sudo dnf install jq
On macOS (with Homebrew):
brew install jq
Step 2: Format and Clean the JSON
If you just want to convert your raw JSON into a properly formatted, valid JSON object (preserving intentional whitespace in values):
jq . your_file.json
This will output nicely indented, valid JSON that any parser can read.
If you also want to strip the extra leading/trailing whitespace from all string values (like the spaces around 192.168.43.221 or Ubuntu), use this command:
jq 'walk(if type == "string" then trim else . end)' your_file.json
The walk function traverses every element in the JSON, and trim removes whitespace from the start and end of strings while leaving internal spaces intact.
Method 2: Use Python (No Extra Installs Needed)
If you can't install jq (e.g., on a locked-down system), Python's built-in json module works perfectly. Most Linux/macOS systems come with Python pre-installed.
Basic Formatting
To turn your raw JSON into a properly formatted object:
python3 -c "import json, sys; data = json.load(sys.stdin); json.dump(data, sys.stdout, indent=2)" < your_file.json
Clean Whitespace from Values
To also strip leading/trailing whitespace from all string values:
python3 -c "import json, sys; data = json.load(sys.stdin); def trim_val(v): return v.strip() if isinstance(v, str) else v cleaned_data = {k: trim_val(v) for k, v in data.items()} json.dump(cleaned_data, sys.stdout, indent=2)" < your_file.json
Why Avoid Sed/Awk?
While you could hack together a solution with sed or awk, those tools aren't designed for JSON. They can easily break your JSON if strings contain special characters (like quotes or backslashes) or if the JSON structure changes later. Stick to dedicated JSON tools for reliability.
内容的提问来源于stack exchange,提问作者Ananth Reddy

