You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell Here-String正确转换为嵌套结构JSON?

将PowerShell Here-String转换为嵌套JSON结构

原代码直接拆分字符串并转换为JSON,得到的是一维数组,无法构建出预期的嵌套层级结构。要实现目标,需要逐行解析每个override条目,提取键路径和对应值,再逐层构建嵌套哈希表,最后转换为JSON。

解决方案代码

# 输入的Here-String
$inputString = @'
override['abc_os_config']['local_administrators']['default_administrators']['abc.com'] = %w {}
override['abc_os_config']['local_administrators']['default_administrators']['devad.abc.com'] = %w {}
override['abc_os_config']['local_administrators']['default_administrators']['qad.abc.com'] = %w {}
override['CIS_Remediation_Windows']['security_options']['lanman_authentication_level'] = 3
'@

# 初始化根哈希表
$rootHash = @{}

# 逐行处理输入内容,跳过空行
foreach ($line in $inputString -split "`n" | Where-Object { $_ -match '\S' }) {
    # 用正则匹配键路径和对应值
    if ($line -match '^override\[(''[^'']+'')\](?:\[(''[^'']+'')\])*\s*=\s*(.*)$') {
        # 提取所有键并去除单引号
        $keys = $matches[1..($matches.Count-2)] -replace "'", ''
        # 提取值并去除多余空格
        $value = $matches[-1].Trim()
        
        # 逐层构建嵌套哈希表
        $currentHash = $rootHash
        for ($i = 0; $i -lt $keys.Count; $i++) {
            $key = $keys[$i]
            # 最后一个键直接赋值
            if ($i -eq $keys.Count - 1) {
                $currentHash[$key] = $value
            } else {
                # 键不存在则创建新的哈希表
                if (-not $currentHash.ContainsKey($key)) {
                    $currentHash[$key] = @{}
                }
                # 进入下一层哈希表
                $currentHash = $currentHash[$key]
            }
        }
    }
}

# 转换为JSON(指定深度确保嵌套层级被完整序列化)
$rootHash | ConvertTo-Json -Depth 100

运行结果

执行代码后将输出预期的嵌套JSON结构:

{
  "abc_os_config": {
    "local_administrators": {
      "default_administrators": {
        "abc.com": "%w {}",
        "devad.abc.com": "%w {}",
        "qad.abc.com": "%w {}"
      }
    }
  },
  "CIS_Remediation_Windows": {
    "security_options": {
      "lanman_authentication_level": "3"
    }
  }
}

内容的提问来源于stack exchange,提问作者Keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:25:18