替代JQ遍历Shell中的JSON数组

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

我有一个对象

items=$(aws dynamodb scan --attributes-to-get Zipcode Id --table-name Test --query "Items[*]" --output json | jq --compact-output '.[]')
for itemValue in $items; do
    aws dynamodb delete-item --table-name Test --key $itemValue
done

它依次删除所有项目。有人可以建议我不使用jq如何实现相同的目的。由于不允许在ec2上使用第三方命令?可以使用任何aws-cli命令来实现吗?

谢谢。

shell unix aws-cli
1个回答
0
投票

原始代码一开始不起作用

# THIS IS BROKEN
json_list='["First Item", "Second Item", "Third Item"]'
for itemValue in $(echo "$json_list" | jq --compact-output '.[]'); do
  echo "Got an item: <$itemValue>"
done

事件:

Got an item: <"First>
Got an item: <Item">
Got an item: <"Second>
Got an item: <Item">
Got an item: <"Third>
Got an item: <Item">

显然,这是不正确的。


正确使用jq需要更好的定界符选择和while read循环

# THIS WORKS
json_list='["First Item", "Second Item", "Third Item"]'
while IFS= read -r -d '' itemValue; do
  echo "Got an item: <$itemValue>"
done < <(jq -j '.[] | (., "\u0000")' <<<"$json_list")

...作为输出发出:

Got an item: <First Item>
Got an item: <Second Item>
Got an item: <Third Item>

相同的答案可以轻松地移植到Python

json_to_nullsep_py=$(cat <<'EOF'
import json
import sys
for item in json.load(sys.stdin):
    sys.stdout.write(item)
    sys.stdout.write('\x00')
EOF
)

json_to_nullsep() {
  python -c "$json_to_nullsep_py" "$@"
}

while IFS= read -r -d '' itemValue; do
  echo "Got an item: <$itemValue>"
done < <(json_to_nullsep <<<"$json_list")

...同样正确地发出:

Got an item: <First Item>
Got an item: <Second Item>
Got an item: <Third Item>
© www.soinside.com 2019 - 2024. All rights reserved.