如何将类似JSON的字符串转换为PowerShell对象?

发布于 2025-02-06 00:36:20 字数 468 浏览 2 评论 0 原文

Microsoft实用程序以以下格式返回字符串:

“作者:first.last; name:rootconfiguration;版本:2.0.0; generationDate; generationDate:06/01/2022 13:18:18:10; generationHost; generationHost:server; server; server;“;”

我想将这些字符串转换为简单的对象。如果这是真正的JSON,我只会使用Convertfrom-Json。为了尽可能少地重新发明轮子,将其转换为对象的最直接方法是什么(用钥匙作者,名称,版本,GenerationDate,GenerationDate,GenerationHost,具有明显的值。

如果“您只需要通过咬咬一下字符串来磨碎”,那就是答案,我可以做到这一点,但似乎应该有一种更简单的方法!)“做您的事情,但是将半刚果作为新线处理,接受右侧的空间等。”

A Microsoft utility returns strings in the following format:

"Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;"

I would like to convert those strings into simple objects. If this were true JSON, I'd just use ConvertFrom-JSON. To reinvent the wheel as little as possible, what's the most straightforward way to convert that into an object (with keys Author, Name, Version, GenerationDate, GenerationHost, with the obvious values. It's fine if the values are all treated as dumb strings.

If "you just have to grind it out by tokenizing the string bite by bite" is the answer, I can do that, but it seems there should be a simpler way, like if I could tell ConvertFrom-JSON (or even ConvertFrom-String!) "Do your thing, but process the semicolons as newlines, accept spaces on the right hand side, etc."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

盛装女皇 2025-02-13 00:36:20
  • 将手动解析与 < /code> ,但是请注意,鉴于后者返回 [Hashtable] 实例,该输入顺序尚未保留,具有固有的无序条目:
# Sampe input string.
$str = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Replace ":" with "=", split into individual lines, so
# that ConvertFrom-StringData recognizes the format.
$str -replace ': ', '=' -replace '; ?', "`n" | ConvertFrom-StringData

# Note: The above outputs a [hashtable].
#       You could cast it to [pscustomobject], as shown below,
#       but the input order of entries is lost either way.

AS zett42 如果输入字符串中包含的 \ chars中的值(与密钥相对)指出,他们'为了保留这样的保留 - 请参阅下面的评论。

  • 仅手动解析的解决方案:
# Sampe input string.
$str = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Initialize an ordered hashtable (dictionary)
$dict = [ordered] @{}

# Split the string by ";", then each entry into key and value by ":".
$str -split '; ?' | 
  ForEach-Object { $key, $value = $_ -split ': ', 2; $dict[$key] = $value }

# Convert the ordered hashtable (dictionary) to a custom object.
[pscustomobject] $dict
  • A solution that combines manual parsing with ConvertFrom-StringData, but note that input order of the entries isn't preserved, given that the latter returns a [hashtable] instance with inherently unordered entries:
# Sampe input string.
$str = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Replace ":" with "=", split into individual lines, so
# that ConvertFrom-StringData recognizes the format.
$str -replace ': ', '=' -replace '; ?', "`n" | ConvertFrom-StringData

# Note: The above outputs a [hashtable].
#       You could cast it to [pscustomobject], as shown below,
#       but the input order of entries is lost either way.

As zett42 points out, if the values (as opposed to the keys) in the input string contained \ chars., they'd need to be doubled in order to be retained as such - see his comment below.

  • A solution with manual parsing only:
# Sampe input string.
$str = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Initialize an ordered hashtable (dictionary)
$dict = [ordered] @{}

# Split the string by ";", then each entry into key and value by ":".
$str -split '; ?' | 
  ForEach-Object { $key, $value = $_ -split ': ', 2; $dict[$key] = $value }

# Convert the ordered hashtable (dictionary) to a custom object.
[pscustomobject] $dict
月光色 2025-02-13 00:36:20

我通常不会回答没有编码尝试的问题,但是认为这可能会对他人有所帮助。鉴于定界符是半龙,我当时想先转换为CSV,但接下来必须担心标题。因此,我们可以使用定界符将结果分开并一次处理一个值:

"Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;".Split(";").Trim() | 
    ForEach-Object -Process {
        $header,$value = $_ -split ":",2
        New-Object -TypeName PSCustomObject @{
            $header = $value
        }
    } | ConvertTo-Json

为了使这项工作我们需要在第一个结肠上分开(:> )将其余的完整留下; INCASE在值中的其他内容就像您在 GenerationDate 属性中看到的那样。

  • 这是使用 $ _ -split“:”,2 实现的。

最后,其余的只是将标题分配给 pscustomObject ,并使用 convertto-json 将结果转换为JSON。


注意:我仅限于我的工作系统上的“严格语言模式”而不是 new-Object

I usually don't answer questions that don't have a coding attempt but, figured this might help others. Given that the delimiter is a semicolon, I was thinking of converting to CSV first but, would have to worry about the header next. So, instead of converting to CSV, we can use the delimiter to split the results at that and process the values one at a time:

"Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;".Split(";").Trim() | 
    ForEach-Object -Process {
        $header,$value = $_ -split ":",2
        New-Object -TypeName PSCustomObject @{
            $header = $value
        }
    } | ConvertTo-Json

To make this work we need to split at just the first colon (:) leaving the rest intact; incase there's others in the value like you see in the GenerationDate property.

  • This was achieved using $_ -split ":",2.

Finally, the rest was just left to assign the header to and value to a PSCustomObject and conver the results to JSON using ConvertTo-Json.


Note: I am restricted to a "strict language mode" on my work system so it's best to use the type-accelarator of [PSCustomObject]@{..} to create the object, rather than New-Object.

单调的奢华 2025-02-13 00:36:20

补充现有有用的答案,这是另一个使用 regex.matches.matches(

$testInput = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Create a temporary, ordered Hashtable to collect keys and values in the original order.
$ht = [ordered] @{}  

# Use a regular expression to find all key/value pairs.
foreach( $match in [regex]::Matches( $testInput, '\s*([^:]+):\s*([^;]+);') ) {
    # Enter a key/value pair into the Hashtable
    $ht[ $match.Groups[1] ] = $match.Groups[2] 
}

# Convert the temporary Hashtable to PSCustomObject.
[PSCustomObject] $ht

Author         : First.Last
Name           : RootConfiguration
Version        : 2.0.0
GenerationDate : 06/01/2022 13:18:10
GenerationHost : Server
  • 正则速率模式由两个捕获组 (),其中第一个捕获a ,第二个捕获a <强>价值。
  • 有关详细说明,请参见 regex101 ,您也可以在其中播放模式。

Complementing the existing helpful answers, here is another one using the Regex.Matches() function:

$testInput = 'Author: First.Last; Name: RootConfiguration; Version: 2.0.0; GenerationDate: 06/01/2022 13:18:10; GenerationHost: Server;'

# Create a temporary, ordered Hashtable to collect keys and values in the original order.
$ht = [ordered] @{}  

# Use a regular expression to find all key/value pairs.
foreach( $match in [regex]::Matches( $testInput, '\s*([^:]+):\s*([^;]+);') ) {
    # Enter a key/value pair into the Hashtable
    $ht[ $match.Groups[1] ] = $match.Groups[2] 
}

# Convert the temporary Hashtable to PSCustomObject.
[PSCustomObject] $ht

Output:

Author         : First.Last
Name           : RootConfiguration
Version        : 2.0.0
GenerationDate : 06/01/2022 13:18:10
GenerationHost : Server
  • The RegEx pattern consists of two capturing groups ( ), where the first one captures a key and the second one captures a value.
  • For a detailed explanation see regex101, where you can also play around with the pattern.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文