1

这是我的情况。我有一个导入PowerShell-JSON库的 PowerShell 模块;此库将 JSON 字符串转换为 PowerShell 对象。我的模块提供了一个到 CouchDB 的接口,所以我的 JSON 字符串是从 HTTP 调用中获得的。我有一个函数,Send-CouchDbRequest它向 CouchDB 发出 HTTP 请求并将响应数据作为字符串返回(响应数据是使用 获取的StreamReader.ReadToEnd())。

在另一个函数中Get-CouchDbDocument,我调用了 Send-CouchDbRequest,并将输出保存在变量中$json。根据$json.GetType()and $json | Get-Member,这是 类型System.String。如果我随后将此字符串输入ConvertFrom-JSON,我希望返回一个PSCustomObject根据提供给它的 JSON 文档定义的属性;相反,我得到一个 PowerShell 哈希表的字符串表示形式,即@{name1=value; name2=value2; name3=value3}. 返回的对象也是System.String基于与上述相同测试的类型,而不是预期的PSCustomObject. 在我看来,PowerShell 在这里进行了某种自动(和不需要/不需要的)类型转换。

该错误不在 PowerShell-JSON 中——我已经与作者讨论过,并且我们都设法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 的代码很长,可以在 GitHub 上找到。在我描述的场景中失败并在其他地方工作的示例 JSON 字符串是:

{"_id":"f42d2e0c5be0a7ab7bdc1cba23fc1d73","_rev":"1-59414e77c768bc202142ac82c2f129de","key":"value"}

有什么想法吗?提前谢谢了。

4

1 回答 1

3

哇,这个很棘手。

对您有帮助的是更改存储对象的变量名称。

$doc = $json | ConvertFrom-JSON
Write-Output $doc

原因:您在param块中指定,该$document变量的类型应该是[string]. 这就是 PowerShell 将尝试将输出从转换ConvertFrom-JSON为字符串的原因。

其他可能的解决方案是指定$document不带类型的参数。

于 2010-04-29T13:34:36.193 回答