如何在Bash中遍历JSON并更新auditX对象的password字段
Fixing the Initial Error
Your original jq command fails because .[] iterates all top-level values, including the string storageSummary. The has() function only works on objects, so calling it on a string throws an error. To fix this, first filter for values that are objects before checking for the auditScore key:
jq '.[] | select(type == "object" and has("auditScore"))' input.json
This command will only return the audit1, audit2, audit3 objects, skipping storageSummary entirely.
Updating Password Fields in the Original JSON
If you want to modify the password fields directly in the JSON file (keeping storageSummary intact), use map_values to conditionally update only the audit objects:
# Replace "new_secure_password" with your desired password jq 'map_values(if type == "object" and has("auditScore") then .password = "new_secure_password" else . end)' input.json > updated_input.json
This will:
- Preserve the
storageSummaryfield as-is - Set the
passwordfield to your new value in all audit objects - Write the modified JSON to
updated_input.json
Processing Audit Objects in a Bash Loop
To integrate this into a Bash loop for custom password updates (e.g., per-satellite passwords), output each audit object as a compact JSON line with -c, then loop through them:
jq -c '.[] | select(type == "object" and has("auditScore"))' input.json | while read -r audit_obj; do # Extract satellite name from the JSON object satellite=$(echo "$audit_obj" | jq -r '.satelliteName') # Replace with your actual password update logic echo "Updating password for satellite: $satellite" # Example: some_command --satellite "$satellite" --new-password "your_custom_pass" # If you need to modify the JSON object and save it separately # echo "$audit_obj" | jq '.password = "custom_pass_for_$satellite"' > "updated_$satellite.json" done
This approach safely handles each audit object individually, letting you run custom operations per satellite.
内容的提问来源于stack exchange,提问作者Burps

