问题描述
我需要一些有关 Node js 中 JSON 到 XML 转换的帮助/建议.我有一个服务,它在需要转换为 XML 的请求正文中获取一个 JSON 对象.我能够使用 node-xml2js 实现这一点,用于最多一层嵌套对象的 json 输入.但是,对于具有属性值的嵌套对象,它会变得更加复杂.属性应该首先被识别,在通过 xml2js 解析之前以 $ 符号为前缀并用花括号括起来得到正确的xml.有没有更好的方法可以简化这个重新格式化json输入的复杂层?xml2js 可以转换:
I need some help/advice with JSON to XML conversion in Node js.I have a service that gets a JSON object in request body that needs to convert to XML. I am able to achieve this using node-xml2js for json inputs with maximum one level of nested objects. But, it gets way more complicated with nested objects having attribute values. Attributes should be identified first, prefixed with $ sign and enclosed in curly braces before parsing through xml2js to get correct xml.Is there a better way of doing this where this complicated layer of reformatting the json input can be simplified?xml2js can converts this:
{
"Level1":{ "$":{ "attribute":"value" },
"Level2": {"$":{"attribute1":"05/29/2020",
"attribute2":"10","attribute3":"Pizza"}}
}
对此:(这是正确的):
to this:(which is correct):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
<Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
但实际的 json 输入是这样的:
But actual json input is this:
{
"Level1":{"attribute":"value",
"Level2": {"attribute1":"05/29/2020",
"attribute2":"10","attribute3":"Pizza"} }
}
预期相同的结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
<Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
如果您曾处理过类似的要求,请告诉我.感谢任何帮助.谢谢你.
Please let me know if you have worked on similar requirements. Appreciate any help.Thank you.
推荐答案
这将是一种将对象改回库中预期格式的方法,尽管它假定所有非对象键都应该是属性(是这是您的应用程序的有效假设吗?)
This would be a way to change the object back to the format expected in the library, although it assumes that all non object keys are supposed to be attributes (is that a valid assumption for your application?)
function groupChildren(obj) {
for(prop in obj) {
if (typeof obj[prop] === 'object') {
groupChildren(obj[prop]);
} else {
obj['$'] = obj['$'] || {};
obj['$'][prop] = obj[prop];
delete obj[prop];
}
}
return obj;
}
然后像这样使用:
var xml2js = require('xml2js');
var obj = {
Level1: {
attribute: 'value',
Level2: {
attribute1: '05/29/2020',
attribute2: '10',
attribute3: 'Pizza'
}
}
};
var builder = new xml2js.Builder();
var xml = builder.buildObject(groupChildren(obj));
打印出来:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
<Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
这篇关于Node JS 服务中的 JSON 到 XML 转换(使用 xml2js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!