Permalink
Browse files

options.textNodeKey specifies the json key for a node's text data. if…

… unspecified, defaults to usual $t.
  • Loading branch information...
1 parent 692b944 commit 1d0aff201ed6f8798ce4c8ac0a95b9c53b584b93 @huned huned committed Feb 1, 2012
Showing with 19 additions and 6 deletions.
  1. +1 −1 README.md
  2. +6 −5 lib/xml2json.js
  3. +12 −0 test/test.js
View
@@ -21,7 +21,7 @@ console.log(json);
```
* if you want to get the Javascript object then you might want to invoke parser.toJson(xml, {object: true});
* if you want a reversible json to xml then you should use parser.toJson(xml, {reversible: true});
-
+* if you want to override the default "$t" key name for a node's text value, specify the textNodeKey option. e.g., `parser.toJson(xml, {textNodeKey: "text"})`
## License
Copyright 2011 BugLabs Inc. All rights reserved.
View
@@ -39,19 +39,19 @@ function text(data) {
if (!data.length) {
return;
}
- currentObject['$t'] = (currentObject['$t'|| "") + data;
+ currentObject[options.textNodeKey] = (currentObject[options.textNodeKey|| "") + data;
}
function endElement(name) {
// This should check to make sure that the name we're ending
// matches the name we started on.
var ancestor = ancestors.pop();
if (!options.reversible) {
- if ((Object.keys(currentObject).length == 1) && ('$t' in currentObject)) {
+ if ((Object.keys(currentObject).length == 1) && (options.textNodeKey in currentObject)) {
if (ancestor[name] instanceof Array) {
- ancestor[name].push(ancestor[name].pop()['$t']);
+ ancestor[name].push(ancestor[name].pop()[options.textNodeKey]);
} else {
- ancestor[name] = currentObject['$t'];
+ ancestor[name] = currentObject[options.textNodeKey];
}
}
}
@@ -71,7 +71,8 @@ module.exports = function(xml, _options) {
options = {
object: false,
- reversible: false
+ reversible: false,
+ textNodeKey: '$t'
};
for (var opt in _options) {
View
@@ -47,3 +47,15 @@ fs.readdir(fixturesPath, function(err, files) {
}
});
+// test options.textNodeKey custom value
+var xml = '<ref href="http://example.com">http://example.com</ref>';
+var actual = parser.toJson(xml, {object: true, textNodeKey: 'hi'});
+var json = '{"ref":{"href":"http://example.com","hi":"http://example.com"}}';
+assert.deepEqual(actual, JSON.parse(json));
+
+// test options.textNodeKey default value
+var actual = parser.toJson(xml, {object: true});
+var json = json.replace('"hi":', '"$t":');
+assert.deepEqual(actual, JSON.parse(json));
+
+console.log('[xml2json options.textNodeKey] passed');

0 comments on commit 1d0aff2

Please sign in to comment.