Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IsArray option isn't parsing tags with 0 as value correctly #490 #557

Merged
merged 1 commit into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions spec/arrayMode_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,37 @@ describe("XMLParser with arrayMode enabled", function () {
expect(result).toEqual(expected);
});

it("should parse leaf tags with zero or false value correctly in arrayMode", function () {
const xmlDataExample = `
<report>
<value>0</value>
<isNew>false</isNew>
<isReport>true</isReport>
</report>`

const expected = {
"report":
[
{
"value": 0,
"isNew": false,
"isReport": true
}
]
};

const options = {
ignoreAttributes: false,
isArray: (tagName, jpath, isLeafNode, isAttribute) => {
if(!isLeafNode) return true;
}
}
const parser = new XMLParser(options);
const result = parser.parse(xmlDataExample);
// console.log(JSON.stringify(result,null,4));
expect(result).toEqual(expected);
});

it("should parse only attributes as Array if set", function () {

const expected = {
Expand Down
14 changes: 13 additions & 1 deletion src/xmlparser/node2json.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,20 @@ function assignAttributes(obj, attrMap, jpath, options){
}

function isLeafTag(obj, options){
const { textNodeName } = options;
const propCount = Object.keys(obj).length;
if( propCount === 0 || (propCount === 1 && obj[options.textNodeName]) ) return true;

if (propCount === 0) {
return true;
}

if (
propCount === 1 &&
(obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
) {
return true;
}

return false;
}
exports.prettify = prettify;