从JSON字符串中提取两个ItemsQueued值的技术求助
Hey there! Since you're not a developer, let's skip the messy sed hacks and use a tool made specifically for JSON called jq — it's way simpler and reliable for this kind of task. Here's a step-by-step guide:
Step 1: Install jq (if you don't have it already)
- On Ubuntu/Debian:
sudo apt update && sudo apt install jq - On CentOS/RHEL:
sudo yum install jq - On macOS (with Homebrew):
brew install jq
Step 2: Prepare your JSON
You can either store the JSON in a file or keep it in a terminal variable.
Option A: JSON in a file
Save your entire JSON string into a text file named data.json.
Option B: JSON in a variable
Run this command in your terminal to store the JSON directly in a variable:
json_data='[{"Description":"blablabla","RemoteServerID":"982734298437234","DisplayClass":101,"ActiveWorkers":0,"TotalWorkers":1,"State":13,"ItemsQueued":0,"BytesQueued":0,"LastWorkerSubmitTime":1592553946,"CurrentTime":1592554151,"ItemsReplicated":456,"BytesReplicated":188588980},{"Description":"blablabla","RemoteServerID":"982734298437234","DisplayClass":100,"ActiveWorkers":0,"TotalWorkers":6,"State":13,"ItemsQueued":0,"BytesQueued":0,"LastWorkerSubmitTime":1592553615,"CurrentTime":1592554151,"ItemsReplicated":403459,"BytesReplicated":1061944812437}]'
Step 3: Extract the
ItemsQueued values into a variable We'll store both values in a bash array so you can access them individually.
If using a file:
# Extract values and store in an array items_queued=($(jq -r '.[].ItemsQueued' data.json))
If using a variable:
# Pipe the variable content to jq and store in an array items_queued=($(echo "$json_data" | jq -r '.[].ItemsQueued'))
Step 4: Use the extracted values
Now you can access the two values like this:
- First
ItemsQueuedvalue:${items_queued[0]} - Second
ItemsQueuedvalue:${items_queued[1]}
To test that it works, run:
echo "First value: ${items_queued[0]}" echo "Second value: ${items_queued[1]}"
You'll see both output 0 (which matches your original JSON data).
Why this is better than sed:
jqis a dedicated JSON parser, so it won't break if your JSON format changes (like field order or extra spaces) — something sed can't guarantee with string matching..[].ItemsQueuedtells jq: "go through each object in the array, and grab theItemsQueuedvalue".- The
-rflag makes jq output raw text instead of quoted strings, which is perfect for storing in variables.
内容的提问来源于stack exchange,提问作者fabian
相关产品推荐
相关产品推荐

