Jul 032014
Article Perl

JSON and XML are to formats commonly used to represent structured data in a text file. Sometimes, data exported from a tool in JSON format needs to be imported in a different tool that only accepts XML as input.

This post explain how to perform the conversion from JSON to XML using a perl script.

1. Reading a JSON file in perl

In perl, reading a JSON file is easily done using the decode_json() routine from the JSON module, as already explained in our previous post: How to read and write JSON files in Perl

2. Writing a XML file in perl

Writing an XML file is also easy in perl, using XML::Simple module. We have also covered reading and writing XML files in perl in our posts:

How to read and write XML files in Perl using XML::Simple


How to read and write XML files in perl using XML::Parse::PerlSAX

3. Converting from JSON to XML

Using the information in the previous posts, a script to convert from JSON to XML can be written as follows:

4. Testing the script

To verify that the script is working as expected, a sample¬†input file “data.json” in JSON format can be used:

The output from the script should be the following data in XML format:

Index of posts related to perl programming

 Posted by at 11:38 am

  2 Responses to “How to convert JSON to XML using Perl”

  1. Hi,

    I have to read newline delimited JSON object.
    ie. one interaction per line.

    something like this.

    {“id”:2,”name”:”Neo”,”tags”:[“whoa”,”knows kungfu”]}
    {“id”:3,”name”:”Egon”,”tags”:[“streams”,”wrong movie”]}

    I have getting one single json file which contain newline delimited JSON object. Can you please help how to read the JSON file and convert into XML


    • Hi again, Neeraj
      The easiest way is to convert the input file “data.json_not_ok” into valid JSON, and then perform the conversion as explained in the post mentioned above.
      On a linux system, The sample data you gave can be converted to valid JSON with the command:

      (echo "["; sed -e '$ ! s/$/,/' data.json_not_ok; echo "]") > data.json

      The output from this command will be a correct JSON-formatted file data.json:

      {"id":2,"name":"Neo","tags":["whoa","knows kungfu"]},
      {"id":3,"name":"Egon","tags":["streams","wrong movie"]}

 Leave a Reply