Chat with us, powered by LiveChat

Blog

Back

Parsing JSON in PowerShell, XML & The member "Item" is already present

8 Aug 2012 by Emma Robinson

I came across an annoying Powershell bug recently whilst working on a project to parse JSON data from the web in Powershell.
I was working with the following script

Add-Type -Assembly System.ServiceModel.Web,System.Runtime.Serialization
function Convert-JsonToXml([string]$json)
{
$bytes = [byte[]][char[]]$json
$quotas = [System.Xml.XmlDictionaryReaderQuotas]::Max
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($bytes,$quotas)
try
{
$xml = new-object System.Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
}
}
#JSON String
$jsonString = '{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}'
#Convert JSON to XML
$xml = Convert-JsonToXml($jsonString)
$menu = $xml.root.menu.popup.menuitem
#Get each menu item and write it to console
foreach ($menuitem in $menu)
{
$menuitem.value."#text"
}

It was just returning no data whatsoever. Annoying.
After a lot of debugging, I noticed that the $menu variable would throw an error when I tried to display it.

PS C:\> $menu
format-default : The member "Item" is already present.
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : AlreadyPresentPSMemberInfoInternalCollectionAdd,Microsoft.PowerShell.Commands.FormatDefa
ultCommand


After a lot of Googling I found an article on CodeProject that pointed me in the right direction. I added the .item to the loop at the bottom of the script and it now works as planned!

#Get each menu item and write it to console
foreach ($menuitem in $menu.item)
{
$menuitem.value."#text"
}