I want to get the length of the JSON, but it's not giving the values i want. I am using XML to JSON converter library (xml2js). If do you know another library than xml2js. I can use it too.
console.log(result.length) -> Returns the 2, which is correct.
{
LISTENER: [
{
CONNECTTIME: { _text: '4880' },
UID: { _text: '57' },
XFF: {},
GRID: { _text: '57' },
TRIGGERS: { _text: '0' }
},
{
CONNECTTIME: { _text: '254' },
UID: { _text: '65' },
XFF: {},
GRID: { _text: '65' },
TRIGGERS: { _text: '0' }
}
]
}
But if i delete one record from the JSON like the below.
console.log(result.length) -> Returns the 9, which is wrong. I want it to be 1. Where am i doing wrong?
{
LISTENER: {
CONNECTTIME: { _text: '4587' },
UID: { _text: '57' },
XFF: {},
GRID: { _text: '57' },
TRIGGERS: { _text: '0' }
}
}
Can someone help me? Is there a any force options to make both records convert to array.
Additional Information For Help;
Here is the code.
var options = {ignoreComment: true, alwaysChildren: true, compact: true}
var result = convert.xml2js(response.data, options);
console.log("listeners.listener:"+Object.keys(result.SHOUTCASTSERVER.LISTENERS.LISTENER).length);
console.log(util.inspect(result.SHOUTCASTSERVER.LISTENERS, false, null, true /* enable colors */))
response.data is the respond of the get request(using axios library) from website. Gives the body of the XML page.
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<SHOUTCASTSERVER>
<LISTENERS>
<LISTENER>
<CONNECTTIME>350</CONNECTTIME>
<UID>66</UID>
<XFF/>
<GRID>66</GRID>
<TRIGGERS>0</TRIGGERS>
</LISTENER>
</LISTENERS>
</SHOUTCASTSERVER>
XML page converting with library (XMLtoJS) Output of the result (If there is 1 record converting like this);
{
_declaration: {
_attributes: { version: '1.0', encoding: 'UTF-8', standalone: 'yes' }
},
SHOUTCASTSERVER: {
LISTENERS: {
LISTENER: {
CONNECTTIME: { _text: '657' },
UID: { _text: '66' },
XFF: {},
GRID: { _text: '66' },
TRIGGERS: { _text: '0' }
}
}
}
}
Output of the result (2 Record Output);
{
_declaration: {
_attributes: { version: '1.0', encoding: 'UTF-8', standalone: 'yes' }
},
SHOUTCASTSERVER: {
LISTENERS: {
LISTENER: [
{
CONNECTTIME: { _text: '819' },
UID: { _text: '66' },
XFF: {},
GRID: { _text: '66' },
TRIGGERS: { _text: '0' }
},
{
CONNECTTIME: { _text: '3' },
UID: { _text: '68' },
XFF: {},
GRID: { _text: '68' },
TRIGGERS: { _text: '0' }
}
]
}
}
}
I found the problem. XMLtoJSON library converts to object if there is 1 record. But if there is 2 or more record, it converts to array.
So in other to fix this, we should add alwaysArray: true
attribute to options.