这是我的情况。我有一个PowerShell模块,它导入PowerShell-JSON库;该库将JSON字符串转换为PowerShell对象。我的模块提供了一个到CouchDB的接口,所以我的JSON字符串是从HTTP调用中获得的。我有一个函数Send-CouchDbRequest
,它向CouchDB发出HTTP请求,并以字符串的形式返回响应数据(响应数据使用StreamReader.ReadToEnd()
获得)。这是PowerShell类型解析机制中的边缘情况吗?
在另一个函数Get-CouchDbDocument
中,我调用了Send-CouchDbRequest,并将输出保存在变量$json
中。根据$json.GetType()
和$json | Get-Member
,这是类型System.String
。如果我然后将此字符串提供给ConvertFrom-JSON
,我希望获得带有根据提供给它的JSON文档定义的属性的PSCustomObject
;相反,我得到了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
}
用于发送-CouchDbRequest的代码是相当长,并且can be found on GitHub。示例JSON字符串在我描述并在别处工作的场景中失败:
{"_id":"f42d2e0c5be0a7ab7bdc1cba23fc1d73","_rev":"1-59414e77c768bc202142ac82c2f129de","key":"value"}
有什么想法?提前谢谢了。
你可以发布'Send-CouchDbRequest'的结果来测试它吗?或者是CodePlex上的问题之一? – stej 2010-04-29 12:02:04
这是来自CodePlex问题的JSON字符串。我会更新这个问题。 – alastairs 2010-04-29 12:48:50