Here's my situation. I have a PowerShell module which imports the PowerShell-JSON library; this library converts JSON strings into PowerShell objects. My module provides an interface to CouchDB, so my JSON strings are obtained from HTTP calls. I have a function, Send-CouchDbRequest
, which makes the HTTP request to CouchDB and returns the response data as a string (the response data is obtained using StreamReader.ReadToEnd()
).
In another function, Get-CouchDbDocument
, I make a call to Send-CouchDbRequest, and save the output in a variable, $json
. According to $json.GetType()
and $json | Get-Member
, this is of type System.String
. If I then feed this string into ConvertFrom-JSON
, I expect to get back a PSCustomObject
with properties defined according to the JSON document supplied to it; instead, I get a string representation of a PowerShell hashtable, i.e., @{name1=value; name2=value2; name3=value3}
. The object returned is also of type System.String
based on the same tests as above, rather than the expected PSCustomObject
. It seems to me that PowerShell is doing some kind of automatic (and unwanted/unneeded) type conversion here.
The bug isn't in PowerShell-JSON - I've already discussed it with the author, and we have both managed to get the same call to ConvertFrom-JSON
to work in a dummy module. I therefore conclude that the error must be in my code somewhere, perhaps a result of the fact that the string has come in over HTTP.
The code for Get-CouchDbDocument is as follows:
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
}
The code for Send-CouchDbRequest is quite lengthy, and can be found on GitHub. The sample JSON string, that fails in the scenario I have described and works elsewhere, is:
{"_id":"f42d2e0c5be0a7ab7bdc1cba23fc1d73","_rev":"1-59414e77c768bc202142ac82c2f129de","key":"value"}
Any thoughts? Many thanks in advance.