我在JSON中有一个对象,其结构如下所示,我想将其转换为一个具有以下结构的“伪3D”关联BASH数组:
SHIPS[$mmsi:mmsi]=367513050
SHIPS[$mmsi:lat]=42.380329
...etc
换句话说,我希望将mmsi
值与每个对象的键结合起来,成为关联数组的索引。
现在,我正在做以下工作,缺点是它依赖于mmsi
字段作为每个JSON对象的第一个字段--这可能是真的,但也不是很可靠。具有所有mmsi
的VESSEL_INDEX
、具有所有现有密钥的KEY_INDEX
以及可以作为VESSEL[$mmsi:$key]
访问的VESSELS
declare -A VESSELS
declare -a VESSEL_INDEX
declare -a KEY_INDEX
while read -r keyvalue
do
key="${keyvalue%%=*}"
value="${keyvalue#*=}"
if [[ "$key" == "mmsi" ]]
then
mmsi="$value"
[[ -n "$mmsi" ]] && VESSEL_INDEX+=("$mmsi")
fi
[[ ! " ${KEY_INDEX[*]} " =~ " ${key} " ]] && KEY_INDEX+=("${key}")
[[ -n "$mmsi" ]] && VESSELS["$mmsi:$key"]="$value"
done <<< "$(curl -sL "$AIS_URL/ships_full.json" | jq -r ".ships[]|to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]")"
这个输入 curl 成:
{
"count": 2
"ships": [
{
"mmsi": 367513050,
"lat": 42.380329,
"lon": -71.042946,
"distance": 0.317654,
"mmsi_type": 1,
"level": -28.161266,
"count": 6895,
"ppm": 4.918982,
"heading": null,
"cog": null,
"speed": 0,
"to_bow": 10,
"to_stern": 17,
"to_starboard": 3,
"to_port": 5,
"shiptype": 52,
"msg_type": 0,
"country": "US",
"status": 0,
"callsign": "WDG2188",
"shipname": "VINCENT D. TIBBETTS",
"destination": "BOSTON",
"last_signal": 0
},
{
"mmsi": 367447520,
"lat": 42.324032,
"lon": -70.994347,
"distance": 3.777312,
"mmsi_type": 1,
"level": -37.657475,
"count": 1103,
"ppm": -1.157407,
"heading": 156,
"cog": 155.5,
"speed": 28.4,
"to_bow": 24,
"to_stern": 20,
"to_starboard": 9,
"to_port": 4,
"shiptype": 40,
"msg_type": 0,
"country": "US",
"status": 0,
"callsign": "WDF4062",
"shipname": "SALACIA",
"destination": "XX XXX>?? ???",
"last_signal": 0
},
],
"error": false
}
1条答案
按热度按时间t98cgbkg1#
使
jq
构造一个declare
语句,使用括号将键括起来,并用@sh
转义:现在您应该能够在Bash中使用关联数组
$SHIPS
:x一个一个一个一个x一个一个二个x