A Simple Way to Convert an XML String to JSON

Sixteen Stars

A Simple Way to Convert an XML String to JSON

While you can create JSON using the tWriteJSONField component, if you want to simply convert an XML String into JSON (with the same format), there is a much simpler way. 

 

All you need to do is use the json-org.jar (which can be downloaded here) and a Talend routine. I have included an example of a routine below.....

package routines;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;



public class XmlToJSON {


    public static String xmlToJson(String xml){
    	String json ="";
    	try {
            JSONObject xmlJSONObj = XML.toJSONObject(xml);
            json = xmlJSONObj.toString();
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
		return json;
    }
        
}

Once you have created the routine, right click on the routine in the project tree and select "Edit Routine Libraries". Then point it towards the Jar downloaded above.

 

Then all you need to do is create your XML, convert it to a String (use a tConvertType), then use your routine method to convert the XML String to a JSON String.

 

Easy Smiley Happy

Four Stars

Re: A Simple Way to Convert an XML String to JSON

Hi Sixteen Stars,

Thank you for tuto. I've been surching a little time for a code like this. First i've found user components named : tConvertXMLtoJSON or the tXMLtoJson. They do the same as your routine. There is only one common think with the components and your routine, the take the xml tree in an intil order but the don't reproduce the same order. Element order is not respected. I don't know why because there is no attributs to specify any order. It's a real problem for me because the transformed JSON has an order to respect because of the API REST need on order (the order i've created in the enter XML) . Do you have an idea about this, please ?

Thank you

Marc.

Highlighted
Sixteen Stars

Re: A Simple Way to Convert an XML String to JSON

Take a look here: https://github.com/stleary/JSON-java/issues/383 

....and here: https://github.com/stleary/JSON-java/wiki/FAQ#why-isnt-ordering-allowed-in-jsonobjects

 

I'm sure this can be achieved, but it shouldn't be needed. There is a recommendation in the first link

 

 

Six Stars

Re: A Simple Way to Convert an XML String to JSON

If the API needs the elements to be in a specific order, then it isn't JSON. It's a custom format that looks a lot like like JSON but has ordering semantics added. You can't expect a generic JSON component to support the requirements of a non-standard data format.

Tutorial

Introduction to Talend Open Studio for Data Integration.

Definitive Guide to Data Integration

Practical steps to developing your data integration strategy.

Definitive Guide to Data Quality

Create systems and workflow to manage clean data ingestion and data transformation.