json - 循环遍历 JSON 数组 shell 脚本
问题描述
我正在尝试编写一个循环遍历 JSON 文件并根据每个对象的属性执行一些逻辑的 shell 脚本。该脚本最初是为 Windows 编写的,但在 MacOS 上无法正常工作。
初始代码如下
documentsJson=""
jsonStrings=$(cat "$file" | jq -c '.[]')
while IFS= read -r document; do
# Get the properties from the docment (json string)
currentKey=$(echo "$document" | jq -r '.Key')
encrypted=$(echo "$document" | jq -r '.IsEncrypted')
# If not encrypted then don't do anything with it
if [[ $encrypted != true ]]; then
echoComment " Skipping '$currentKey' as it's not marked for encryption"
documentsJson+="$document,"
continue
fi
//some more code
done <<< $jsonStrings
在 MacO 上运行时,会立即处理整个文件,因此它不会遍历对象。在尝试了很多建议之后,我最接近它的工作如下:
jq -r '.[]' "$file" | while read i; do
for config in $i ; do
currentKey=$(echo "$config" | jq -r '.Key')
echo "$currentKey"
done
done
控制台结果是parse error: Invalid numeric literal at line 1, column 6
我只是找不到获取 JSON 对象并读取其属性的正确方法。
JSON 文件示例
[
{
"Key": "PdfMargins",
"Value": {
"Left":0,
"Right":0,
"Top":20,
"Bottom":15
}
},
{
"Key": "configUrl",
"Value": "someUrl",
"IsEncrypted": true
}
]
先感谢您!
解决方案
尝试把$jsonStrings
双引号:done <<< "$jsonStrings"
否则,标准外壳拆分适用于变量扩展,您可能希望保留jq
.
你也可以在bash
:
while IFS= read -r document; do
...
done < <(jq -c '.[]' < "$file")
这样可以节省一些资源。不过,我不确定能否在 MacOS 上进行这项工作,因此请先进行测试。
推荐阅读
- windows - Docker Compose - 启动已经创建的容器
- c# - 计算实时并发流的数量
- caching - Laravel 7 Cache via Middleware 未访问缓存内容并发送 X-Proxy-Cache: MISS 标头
- ios - 如何使用 HMAccessoryPayLoad 添加 HomeKit 配件?
- html - 将css应用于内部(移动)
- gcc - Intel 线程积木 gcc 版本
- tensorflow - 如何将 PoseNet ResNet50 tfjs 模型转换为 tflite?
- amazon-ec2 - 使用 Terraform 通过 EC2 创建时,如何向 AWS EBS 添加标签?
- java - servlet [dispatcherServlet] 的 Servlet.service() 在路径 [] 的上下文中抛出异常 NullPointerException
- mysql - 重构 MySQL 表,为每个 id 创建一列