首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell ConvertTo-json输出为小写

Powershell ConvertTo-json输出为小写
EN

Stack Overflow用户
提问于 2014-05-27 06:00:52
回答 4查看 1.5K关注 0票数 1

我使用下面的命令来生成下面的输出

代码语言:javascript
复制
$VMHost | ConvertTo-json | Out-File -encoding "UTF8" -FilePath  ".\$VMHostName.report"

但是我需要所有的小写关键字和值,如下所示

代码语言:javascript
复制
 "HostNumaStatus": [
      {
         "ComputerName": "TEMSA10",
         "MemoryAvailable": 3119,
         "MemoryTotal": 6075,
         "NodeId": 0,
         "ProcessorsAvailability": "35 41 56 58"
      }
   ]

代码语言:javascript
复制
 "hostnumastatus": [
      {
         "computername": "TEMSA10",
         "memroyavailable": 3119,
         "memroytotal": 6075,
         "nodeid": 0,
         "processoravailability": "35 41 56 58"
      }
   ]
EN

回答 4

Stack Overflow用户

发布于 2014-05-27 14:40:19

我会使用[Regex]静态方法Replace

代码语言:javascript
复制
$Json = $VMHost | ConvertTo-Json

[regex]::Replace(
    $Json,
    '(?<=")(\w+)(?=":)',
    {
        $args[0].Groups[1].Value.ToLower()

    }
)
票数 3
EN

Stack Overflow用户

发布于 2014-05-27 06:32:56

将此代码放在$VMHost和ConvertTo-JSON之间。

代码语言:javascript
复制
Select -Property @{N='computername';E={$_.ComputerName}}, @{N='memoryavailable';E={$_.MemoryAvailable}}, @{N='memorytotal';E={$_.MemoryTotal}}, @{N='nodeid';E={$_.NodeId}}, @{N='processorsavailability';E={$_.ProcessorsAvailability}}

因为这些列不是静态的,所以尝试这样做:

代码语言:javascript
复制
$cols = $VMHost | select * | Get-Member | ForEach-Object {@{N=$_.Name.ToLower();E=$_.Name}}
$VMHost | Select -Property $cols | ConvertTo-Json | Out-File -encoding "UTF8" -FilePath  ".\$VMHostName.report"

我真的很想在转换之前对对象进行编辑,但这会得到您想要的最终结果:

代码语言:javascript
复制
# Get the JSON text
$JSON = $VMHost | ConvertTo-Json

# Loop through each line of the JSON output
$JSON.Split("`n") | ForEach-Object {
    # Split the line on the ":", grab the first portion, and trim the space
    $value = $_.Split(":")[0].Trim()
    # Check to see if both the start and end characters are quotes (these should be the key fields)
    if (($value.Substring(0,1) -eq "`"") -and ($value.Substring($value.Length-1,1) -eq "`"")) {
        # If it's a key make it lowercase
        $_.Replace($value,$value.ToLower())
        } else {
        # Otherwise leave it as-is
        $_
        }
    # Output
    } | Out-File -encoding "UTF8" -FilePath  ".\$VMHostName.report"
票数 1
EN

Stack Overflow用户

发布于 2014-05-27 12:09:50

这不是最好的解决方案,而是等待更好的解决方案的拐杖。

代码语言:javascript
复制
# Get the JSON text
$JSON = $VMHost | ConvertTo-Json
$JSON.Split("`n") | % {if($_ -match "(.*):(.*)"){$_ -replace '(.*):(.*)',"$($matches[1].ToLower()):$($matches[2])"}else{$_}}

我使用正则表达式将所有键转换为小写,这必须用各种JSON进行测试

也许有人能提供更好的语法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23878240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档