arrays - 用不同的数组值替换 JSON 中的符号
问题描述
我有 2 个文件 text.json包含
{
"Files": [
{
"pattern": "/Something/Something/*"
},
{
"pattern": "/Something/Something/*"
},
{
"pattern": "/Something/Something/*"
},
{
"pattern": "/Something/Something/*"
},
{
"pattern": "/Something/Something/*"
},
{
"pattern": "/Something/Something/*"
}
]
}
和dlls.txt
1.dll
2.dll
..
6.dll
我想用必要的dll替换符号*,如下所示:
"Files": [
{
"pattern": "/Something/Something/1.dll"
},
{
"pattern": "/Something/Something/2.dll"
},
.
.
.
{
"pattern": "/Something/Something/6.dll"
}
]
}
到目前为止,我的代码替换了符号,但只替换了最后一个数组元素。
解决方案
由于您正在处理结构化数据格式 - JSON - 使用专用解析器总是比基于正则表达式执行纯文本处理更可取。
虽然使用 dedicatedConvertFrom-Json
和ConvertTo-Json
cmdlet 从 JSON 解析和序列化回 JSON比文本处理慢,但它更健壮。
# Read the DLL names from the text file into an array of strings.
$dlls = Get-Content dlls.txt
# Read the JSON file and parse it into an object.
$objFromJson = Get-Content -Raw text.json | ConvertFrom-Json
# Loop over all elements of the array in the .Files property and
# update their .pattern property based on the corresponding DLL names.
$i = 0
$objFromJson.Files.ForEach({
$_.pattern = $_.pattern -replace '(?<=/)\*$', $dlls[$i++]
})
# Convert the updated object back to JSON; save to a file as needed.
$objFromJson | ConvertTo-Json
推荐阅读
- java - 为什么在 HashMap 节点中维护键的哈希?
- laravel - vue.js 未在浏览器中显示
- react-native - Text.js 的这种变化是否会影响任何事情,是否有必要?
- php - 特定位置的 nginx 重写规则
- css - laravel 中的 Boostrap 粘性页脚
- python - 使用 df.to_excel (openpyxl) 从数据框写入时如何在 Excel 中增加行
- javascript - 为什么我不能在 index.js 中使用导出的路由
- cmake - Percona5.7 cmake 在 centos 7 上失败
- mysql - 如何为 wiki 家族建立数据库?
- java - Java - 如何测试 Catch 块?