使用 Bash 通过 jq 从 JSON 中提取特定数据到 CSV

问题描述 投票:0回答:1

我正在编写一个脚本来从 JSON 数组中提取特定数据并将其转换为 CSV。我正在从 API 检索数据,数据如下所示:

"data": [
{
"id": "345",
"market": "storage",
"name": "StorageHub",
"description": null,
"address_line1": "100 Main St",
"address_city": "Cleveland",
"address_state": "OH",
"address_country": "USA",
"address_postal_code": "91801",
"address_latitude": 42.433243,
"address_longitude": -82.3941872,
}
]
}

我只想将 ID、市场、名称和城市提取到名为 {account_id}_exercise1.csv 的新 CSV 中,其中帐户 ID 来自变量。下面的代码成功返回一个 csv,但包含上述数据集中的所有数据,而不仅仅是我想要的 4 个日期片段。

account_id=398

GET "accounts/${account_id}/properties" csv > "files/${account_id}_exercise1.csv" | while read -r row; do
    asset_id=$(echo "$row" | jq -r '.id')
    asset_name=$(echo "$row" | jq -r '.name')
    market_detail=$(echo "$row" | jq -r '.market')
    unit_count=$(echo "$row" | jq -r '.unit_count')

    echo "Property: ${account_id} completed.."  

done
json bash jq export-to-csv
1个回答
0
投票

您需要修改脚本以仅提取特定字段(id、market、name 和 address_city),然后将它们格式化为 CSV 格式。您可以使用 jq 过滤 JSON 数据,然后使用 awk 或其他文本处理工具将输出格式化为 CSV 来实现此目的。

account_id=398

# Get JSON data from API and filter specific fields using jq
data=$(GET "accounts/${account_id}/properties" | jq -r '.data[] | {id, market, name, address_city}')

# Format the filtered data into CSV format
echo "id,market,name,address_city" > "files/${account_id}_exercise1.csv"  # Header
echo "$data" | jq -r '(.id // ""), (.market // ""), (.name // ""), (.address_city // "") | @csv' >> "files/${account_id}_exercise1.csv"
© www.soinside.com 2019 - 2024. All rights reserved.