【发布时间】:2016-11-28 15:07:30
【问题描述】:
ConvertFrom-Json 失败并显示消息“无法处理参数,因为“名称”的值无效。”
"{ """": ""test""}" | ConvertFrom-Json
有没有比手动操作更好的方法?
【问题讨论】:
标签: json powershell-4.0
ConvertFrom-Json 失败并显示消息“无法处理参数,因为“名称”的值无效。”
"{ """": ""test""}" | ConvertFrom-Json
有没有比手动操作更好的方法?
【问题讨论】:
标签: json powershell-4.0
虽然JSON RFC 确实允许空键[1]
, ConvertFrom-Json 确实不,不幸的是,出于技术原因:它返回类型为[pscustomobject] 的对象,不允许这些对象具有名称为空字符串的属性.
相比之下,PowerShell 的 [hashtable] ([System.Collections.Hashtable]) 类型及其有序键兄弟 ([System.Collections.Specialized.OrderedDictionary])do 允许具有空字符串键值的条目(每个实例 1 个)。
ConvertFrom-Json 不提供创建哈希表,但第三方newtonsoft.json 模块 提供。该模块是广泛使用的包装器和Microsoft-recommendedJson.NET library。它带有替代 cmdlet ConvertFrom-JsonNewtonsoft 和 ConvertTo-JsonNewtonsoft:
PS> '{ "": "test"}' | ConvertFrom-JsonNewtonsoft
Name Value
---- -----
test
更新,截至 2020 年 10 月:该模块最后一次更新是在 2019 年 5 月,捆绑的 Newtonsoft.Json.dll 程序集相当旧:版本为 8.0 ,而撰写本文时的current 版本是12.0。该模块的源代码可以在here找到。
输出类型为[System.Collections.Specialized.OrderedDictionary],即带有有序键的哈希表,在这种情况下相当于以下有序哈希表文字:[ordered] @{ '' = 'test' }
您可以使用.'' 或[''] 来引用带有空键的条目:
PS> $o = $'{ "": "test"}' | ConvertFrom-JsonNewtonsoft
PS> $o.'', $o['']
test
test
在没有额外设置的 PowerShell v5 中,以及在安装 PowerShell PackageManagement modules 后的 v4(以及 v3)中,您可以从 elevated 控制台从 PowerShell Gallery 安装模块,如下所示:
Install-Module Newtonsoft.Json
或者,使用Install-Module -Scope CurrentUser Newtonsoft.Json 仅为当前用户安装。
[1] JSON 名称(键)定义为string (member = 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
【讨论】: