Converting JSON to XML and Vice Versa

Let’s learn how to convert records between the JSON and XML formats.

We'll cover the following

We are going to produce a utility that converts records between the JSON and XML formats. The input is given as a command-line argument. The utility tries to guess the format of the input starting from XML. If xml.Unmarshal() fails, then the utility tries using json.Unmarshal(). If there is not a match, then the user is informed about the error condition. On the other hand, if xml.Unmarshal() is successful, the data is stored in an XMLrec variable and is then converted into a JSONrec variable. The same happens with json.Unmarshal() in the case where the xml.Unmarshal() call is unsuccessful.

Coding example

Let’s examine the Go structures we’ll use in this utility:

Get hands-on with 1200+ tech skills courses.