在 powershell 中用空字符串键解析 json

Parse json with empy string key in powershell

ConvertFrom-Json 失败并显示消息 "Cannot process argument because value of "name“无效。” "{ """": ""test""}" | ConvertFrom-Json

有没有比手动操作更好的方法?

虽然 JSON RFC 允许空键[1] , ConvertFrom-Json 而不是 , 不幸的是, 由于技术原因: 它 returns 类型 [pscustomobject] 的对象,不允许有名称为空字符串的 属性。

相比之下,PowerShell 的 [hashtable] ([System.Collections.Hashtable]) 类型及其有序键兄弟 ([System.Collections.Specialized.OrderedDictionary]) do 允许条目为空-字符串键值(每个实例 1 个)。

ConvertFrom-Json 不提供创建哈希表的功能,但是 第三方 newtonsoft.json module does. The module is a wrapper around the widely used and Microsoft-recommended Json.NET library。它带有替代 cmdlet ConvertFrom-JsonNewtonsoftConvertTo-JsonNewtonsoft:

PS> '{ "": "test"}' | ConvertFrom-JsonNewtonsoft

Name                           Value
----                           -----
                               test

更新,截至 2020 年 10 月:该模块最后更新于 2019 年 5 月,捆绑的 Newtonsoft.Json.dll 程序集非常旧: 是版本 8.0,而 current version as of this writing is 12.0. The module's source code can be found here.

输出类型为 [System.Collections.Specialized.OrderedDictionary],即具有有序键的哈希表,在本例中相当于以下有序哈希表文字:
[ordered] @{ '' = 'test' }

您可以使用 .''[''] 来引用带有空键的条目:

PS> $o = $'{ "": "test"}' | ConvertFrom-JsonNewtonsoft
PS> $o.'', $o['']
test
test

安装

在没有额外设置的 PowerShell v5 中,在 v4(以及 v3)中安装 PowerShell PackageManagement modules, you can install the module from the PowerShell Gallery 后,从 elevated 控制台如下:

Install-Module Newtonsoft.Json

或者,使用 Install-Module -Scope CurrentUser Newtonsoft.Json 只为当前用户安装。


[1]一个JSON名字(key)被定义为一个stringmember = string name-separator value),一个“字符串是零个或多个 Unicode 字符”(强调)。

至少在 PowerShell 7.1.3 中,ConvertFrom-Json 有一个允许它处理空键的开关 -AsHashTable

PS> '{ "": "test" }' | ConvertFrom-Json
ConvertFrom-Json: The provided JSON includes a property whose name is an empty string, this is only supported using the -AsHashTable switch.

PS> '{ "": "test" }' | ConvertFrom-Json -AsHashTable

Name    Value
----    -----
        test