我有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-使用专用解析器始终比使用基于正则表达式的纯文本处理更好地使用。
尽管使用专用的 ConvertFrom-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
关于arrays - 用不同的数组值替换JSON中的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62903128/