Cannot save output to variable


There's some odd behaviour when I try to save the result of a call to ConvertFrom-JSON to a variable: the output is not properly stored. Writing the variable to the command results in a hash-table format output of @{ key=value; key1=value1; } and trying to access the properties on the object using the syntax $variable.key returns null. I've tried the following options:
'<JSON string>' | ConvertFrom-JSON
ConvertFrom-JSON -json '<JSON string>'
Note that I am dot-sourcing the ConvertFrom-JSON.ps1 script file into a PowerShell script module (.psm1). The JSON string is valid. Attempting the same thing from the command line (dot-sourcing the file and running the same JSON string against the function) works as expected. The parsed New-Object command from your function is:
(New-Object PSObject | Add-Member -Passthru NoteProperty "id" "f42d2e0c5be0a7ab7bdc1cba23fc1d73"| Add-Member -Passthru NoteProperty "rev" "159414e77c768bc202142ac82c2f129de"| Add-Member -Passthru NoteProperty "key" "value")
Please let me know if you need any further information.


dfinke wrote Apr 27, 2010 at 3:25 AM

Thanks to posting the issue. Please post a sample of the JSON and I will take a look.

alastairs wrote Apr 27, 2010 at 9:05 AM

Many thanks for your quick reply. The JSON string is obtained from an HTTP call; the following string exhibits the faulty behaviour.


Hope that helps.

dfinke wrote Apr 29, 2010 at 1:29 AM

Here is how I setup a psm1 file to test. It works but I am not downloading it via HTTP

. $psScriptRoot\ConvertFrom-JSON.ps1

Function Invoke-Test {
$j = '{"_id":"f42d2e0c5be0a7ab7bdc1cba23fc1d73","_rev":"1-59414e77c768bc202142ac82c2f129de","key":"value"}'
$j | ConvertFrom-JSON

alastairs wrote Apr 29, 2010 at 9:21 AM

Ok, many thanks for looking into it; sorry for wasting your time. There must be something funny about the string in my module, I guess.

alastairs wrote Apr 29, 2010 at 9:58 AM

FWIW, after some further investigation, PowerShell appears to be treating the returned object as a string rather than a PSObject/PSCustomObject. If I feed the output into Get-Member, I get a bunch of information relating to System.String; if I feed the output of your test module into Get-Member, I get a bunch of information relating to PSCustomObject, with the appropriate properties.

Feel free to close this issue off, as I think we're agreed it's not your script that's the issue! :-)

wrote Feb 14, 2013 at 7:31 PM