首页 > 解决方案 > 用不同的数组值替换 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"
        }
    ]
}

到目前为止,我的代码替换了符号,但只替换了最后一个数组元素。

标签: arraysjsonpowershell

解决方案


由于您正在处理结构化数据格式 - JSON - 使用专用解析器总是比基于正则表达式执行纯文本处理更可取。

虽然使用 dedicatedConvertFrom-JsonConvertTo-Jsoncmdlet 从 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

推荐阅读