问题
我正在尝试将 JSON 转换为 XML,但我没有得到确切的输出。在我的 JSON 中,它没有将其转换为 XML 数组
- var InputJSON = "{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}";
- var output = eval("OBJtoXML("+InputJSON+");")
- function OBJtoXML(obj) {
- var xml = '';
- for (var prop in obj) {
- xml += "<" + prop + ">";
- if(obj[prop] instanceof Array) {
- for (var array in obj[prop]) {
- xml += OBJtoXML(new Object(obj[prop][array]));
- }
- } else if (typeof obj[prop] == "object") {
- xml += OBJtoXML(new Object(obj[prop]));
- } else {
- xml += obj[prop];
- }
- xml += "</" + prop + ">";
- }
- var xml = xml.replace(/<\/?[0-9]{1,}>/g,'');
- return xml
- }
复制代码
实际生产:
- <body>
- <entry>
- <fullURL>abcd</fullURL>
- <Resource>1234</Resource>
- <fullURL>efgh</fullURL>
- <Resource>5678</Resource>
- </entry>
- </body>
复制代码
预期输出:
- <body>
- <entry>
- <fullURL>abcd</fullURL>
- <Resource>1234</Resource>
- </entry>
- <entry>
- <fullURL>efgh</fullURL>
- <Resource>5678</Resource>
- </entry>
- </body>
复制代码
如果我在代码中遗漏了任何内容,请指导我达到预期的结果
回答
将 OBJtoXML 函数替换为
- function OBJtoXML(obj) {
- var xml = '';
- for (var prop in obj) {
- xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
- if (obj[prop] instanceof Array) {
- for (var array in obj[prop]) {
- xml += "<" + prop + ">";
- xml += OBJtoXML(new Object(obj[prop][array]));
- xml += "</" + prop + ">";
- }
- } else if (typeof obj[prop] == "object") {
- xml += OBJtoXML(new Object(obj[prop]));
- } else {
- xml += obj[prop];
- }
- xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
- }
- var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
- return xml
- }
复制代码
|