Convert XML to specific JSON structure with powershell

Question:

Need a help on converting an xml to a specific json structure.
XML would look like this,

There can be one or more files in above format, my requirement is to read all those files and group them by Owner and call a REST web service by converting those object to JSON. Required JSON format will be as follows.

}

This need to be done using windows powershell, Iam a java guy and have no idea how to do it using powershell except calling remote ftp server and read all xml files.
Really appreciate, if someone could help me this.

Answer:

XML Stuff

Powershell has some stuff for working with XML. First, it has a native [XML] datatype. You can cast strings to XML like so:

The ConvertTo-Xml cmdlet takes a string or other object and converts it to XML, either as a Document (XML object), a string, or a stream (array of strings). You can pass to it a string, or an object:

Reading From a File:

Working with XML Objects

Once you’ve got your object, you can access nodes as properties:

You can also use XPATH to select a single node or multiple nodes:

Or to do it in a more powershell way you might use the Select-Xml cmdlet:

I’m leaving out a lot of other stuff, especially manipulation, because it seems like you just need to find information and group it together.

JSON Stuff

There isn’t a lot to know about JSON in powershell.

Use ConvertFrom-JSON to convert existing JSON into an object, and use ConvertTo-JSON to convert an object into a JSON string.

Hashtables

Sometimes called hashes or associate arrays, as I’m sure you’re aware. In Powershell you use them like this:

The value can be an array, an object, another hash, etc.

REST

Invoke-RestMethod is the easiest way to make REST calls in Powershell (requires version 3.0+).

How to Proceed

Once you’re able to parse the information out of the XML, build a nested hash or array of hashes that contains the structure you want, and then convert it to JSON:

Take special note of how arrays and hashes are represented in the resulting JSON and maybe change the way you’re building them to get the output you want.

If you have specific questions about a particular method or piece of code, then post specific questions on SO about that piece of it.

References

XML

JSON

REST

Source:

Convert XML to specific JSON structure with powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply