gpt4 book ai didi

arrays - 用不同的数组值替换JSON中的符号

转载 作者:行者123 更新时间:2023-12-03 00:56:22 24 4
gpt4 key购买 nike

我有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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com