Getting extra variable in XML to JSON conversion using perl

Viewed 71

My Program is giving extra variable $t in output. Can anyone help me on this?

use XML::XML2JSON;

xml content

my $XML = '<file><sno>1</sno><process>VALID</process><validation_type>C</validation_type><file_type>HTML</file_type><line>2</line><column>78</column><status>0</status><type>Warning</type><code>001</code><rule>aligning content.</rule><desc>Check that non-breaking space.</desc></file>';
  


my $XML2JSON = XML::XML2JSON->new();
my $JSON = $XML2JSON->convert($XML);
print $JSON;

Output - Extra variable is coming $t

{
    "@encoding": "UTF-8",
    "@version": "1.0",
    "file": {
        "status": {
            "$t": "0"
        },
        "rule": {
            "$t": "aligning content."
        },
        "validation_type": {
            "$t": "C"
        },
        "process": {
            "$t": "VALID"
        },
        "sno": {
            "$t": "1"
        },
        "file_type": {
            "$t": "HTML"
        },
        "desc": {
            "$t": "Check that non-breaking space."
        },
        "type": {
            "$t": "Warning"
        },
        "code": {
            "$t": "001"
        },
        "line": {
            "$t": "2"
        },
        "column": {
            "$t": "78"
        }
    }
}

Expected output is:

{
   "sno": "1",
   "process": "VALID",
   "validation_type": "C",
   "file_type": "HTML",
   "line": "2",
   "column": "78",
   "status": "0",
   "type": "Warning",
   "code": "001",
   "rule": "aligning content.",
   "desc": "Check that non-breaking space."
}
1 Answers

The $t is content key as mentioned in the XML::XML2JSON documentation.


If your intention is to convert from XML to JSON, I would recommend to use XML::Simple and later you can encode using JSON.pm.

Code below:

#!/usr/bin/perl

use strict;
use warnings;

use JSON;
use XML::Simple;

#Create an object
my $xmlSimple = new XML::Simple;

my $XML = '<file><sno>1</sno><process>VALID</process><validation_type>C</validation_type><file_type>HTML</file_type><line>2</line><column>78</column><status>0</status><type>Warning</type><code>001</code><rule>aligning content.</rule><desc>Check that non-breaking space.</desc></file>';

#either we can pass a variable or a xml file which contains xml data
my $dataXML = $xmlSimple->XMLin($XML); 

my $jsonString = encode_json($dataXML);

print $jsonString;

Output:

{
    "process":"VALID",
    "line":"2",
    "column":"78",
    "type":"Warning",
    "file_type":"HTML",
    "sno":"1",
    "status":"0",
    "rule":"aligning content.",
    "code":"001",
    "desc":"Check that non-breaking space.",
    "validation_type":"C"
}
Related