【发布时间】:2010-04-29 08:57:19
【问题描述】:
这是我的情况。我有一个导入 PowerShell-JSON 库的 PowerShell 模块;此库将 JSON 字符串转换为 PowerShell 对象。我的模块提供了一个到 CouchDB 的接口,所以我的 JSON 字符串是从 HTTP 调用中获得的。我有一个函数Send-CouchDbRequest,它向CouchDB 发出HTTP 请求并将响应数据作为字符串返回(响应数据是使用StreamReader.ReadToEnd() 获得的)。
在另一个函数Get-CouchDbDocument 中,我调用了Send-CouchDbRequest,并将输出保存在一个变量$json 中。根据$json.GetType() 和$json | Get-Member,这是System.String 类型。如果我随后将此字符串输入ConvertFrom-JSON,我希望返回一个PSCustomObject,其属性根据提供给它的JSON 文档定义;相反,我得到一个 PowerShell 哈希表的字符串表示形式,即@{name1=value; name2=value2; name3=value3}。根据与上述相同的测试,返回的对象也是System.String 类型,而不是预期的PSCustomObject。在我看来,PowerShell 在这里进行了某种自动(和不需要/不需要的)类型转换。
该错误不在 PowerShell-JSON 中 - 我已经 discussed it with the author,并且我们都设法获得了对 ConvertFrom-JSON 的相同调用以在虚拟模块中工作。因此,我得出结论,错误一定在我的代码中某处,可能是字符串通过 HTTP 进入的结果。
Get-CouchDbDocument 的代码如下:
function Get-CouchDbDocument {
param(
[string] $document = $(throw "Document ID is required."),
[string] $database = $(throw "Database name is required."),
[string] $server = "127.0.01",
[int] $port = 5984
)
$json = Send-CouchDbRequest -dbHost $server -port $port -database $database -document $document -includeDoc
$document = $json | ConvertFrom-JSON
Write-Output $document
}
Send-CouchDbRequest 的代码很长,can be found on GitHub。在我描述的场景中失败并在其他地方工作的示例 JSON 字符串是:
{"_id":"f42d2e0c5be0a7ab7bdc1cba23fc1d73","_rev":"1-59414e77c768bc202142ac82c2f129de","key":"value"}
有什么想法吗?非常感谢。
【问题讨论】:
-
你能发布来自
Send-CouchDbRequest的结果来测试它吗?还是 CodePlex 上的那个问题? -
这是来自 CodePlex 问题的 JSON 字符串。我会更新问题。
标签: powershell types type-conversion powershell-2.0