PowerShell 将字符串转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33217907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:06:09  来源:igfitidea点击:

PowerShell convert string to json

jsonpowershell

提问by developer82

In PowerShell I have the following string that I read from file and need to convert to json:

在 PowerShell 中,我从文件中读取了以下字符串,需要转换为 json:

"@{Account='User01';Domain='Domain01';Admin='True'}"

In my PS script I try to do this (simplified):

在我的 PS 脚本中,我尝试这样做(简化):

$myStr = "@{Account='User01';Domain='Domain01';Admin='True'}" | ConvertTo-Json
$mystr

the result of myStris:

结果myStr是:

"@{Account=\u0027User01\u0027;Domain=\u0027Domain01\u0027;Admin=\u0027True\u0027}"

and not a json I can use. note that the @sign at the beginning of the string is what I get from the file.

而不是我可以使用的 json。请注意,@字符串开头的符号是我从文件中得到的。

How can I convert it to an object I can use?

如何将其转换为我可以使用的对象?

回答by Anthony Neace

You could try some string manipulation to get it in an expected JSON format, and then use ConvertFrom-Jsonto convert it to a PSCustomObject.

您可以尝试一些字符串操作ConvertFrom-Json以将其转换为预期的 JSON 格式,然后将其转换为PSCustomObject

Simple Example: (simple because this assumes that these characters being replaced will only be delimiters)

简单示例:(很简单,因为这假设被替换的这些字符只会是分隔符)

# First, clean up the string.
PS C:\> $mystring = "@{Account='User01';Domain='Domain01';Admin='True'}"
PS C:\> $mystring = $mystring -replace "^@", ""
PS C:\> $mystring = $mystring -replace "=", ":"
PS C:\> $mystring = $mystring -replace ";", ","
PS C:\> $mystring
{Account:'User01',Domain:'Domain01',Admin:'True'}

# Afterwards, convert to PSCustomObject.
PS C:\> $myobject = $mystring | ConvertFrom-Json
PS C:\> $myobject

Account                                 Domain                                  Admin
-------                                 ------                                  -----
User01                                  Domain01                                True

This can also be converted back to JSON:

这也可以转换回 JSON:

PS C:\> $myobject | ConvertTo-Json
{
    "Account":  "User01",
    "Domain":  "Domain01",
    "Admin":  "True"
}