使用Javascript将JSON转换为XML

qacovj5a  于 2023-05-02  发布在  Java
关注(0)|答案(8)|浏览(208)

我试图将JSON转换为XML,但没有得到确切的输出。在我的JSON中有数组对象,它不转换为XML数组。主要是数组对象未按预期转换为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>

请指导我,如果我从代码中缺少任何东西,以获得我的预期结果

ep6jt1vc

ep6jt1vc1#

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
}
lskq00tm

lskq00tm2#

使用xml-js lib

import { json2xml } from "xml-js";

const input = {
  contact: {
    name: `John & cia "example"`
  }
};
const xml = json2xml(input, {
  compact: true
});

// <contact><name>John &amp; cia \"example\"</name></contact>

https://codesandbox.io/s/xml-json-forked-zgit4?file=/src/index.js:97-103
:)

bcs8qyzn

bcs8qyzn3#

这里有几个问题,对于初学者来说,这里的JSON字符串变量要么需要转义它的引号。或者用单引号括起来。例如:

var InputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';

接下来,这里不需要使用eval,当在JavaScript中使用JSON时,应该使用JSON.parse

// First parse the JSON
var InputJSON = JSON.parse(InputJSON);

// Now execute the 'OBJtoXML' function
var output = OBJtoXML(InputJSON);

现在我们来看看这个问题的核心,为什么entry只出现一次?您遇到的问题是xml += "<" + prop + ">";xml += "</" + prop + ">";在每个属性中只发生一次。可能的解决方案如下所示:

function OBJtoXML(obj) {
    var xml = '';
    for (var prop in obj) {
        xml += "<" + prop + ">";
        if(Array.isArray(obj[prop])) {
            for (var array of obj[prop]) {

                // A real botch fix here
                xml += "</" + prop + ">";
                xml += "<" + prop + ">";

                xml += OBJtoXML(new Object(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
}
zlwx9yxi

zlwx9yxi4#

Xml-to-json库有方法jsonToXml(json)xmlToJson(xml)
https://xmltojson.github.io

var inputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';

var xml = jsonToXml(inputJSON);

// <?xml version="1.0" encoding="UTF-8"?>
// <body>
//   <entry>
//     <fullURL>abcd</fullURL>
//     <Resource>1234</Resource>
//   </entry>
//   <entry>
//     <fullURL>efgh</fullURL>
//     <Resource>5678</Resource>
//   </entry>
// </body>
w3nuxt5m

w3nuxt5m5#

var inputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
var parsedInput = JSON.parse(inputJSON);

function OBJtoXML(obj) {
    var xml = '';
    for (var prop in obj) {
        if (obj[prop] instanceof Array) {
            for (var array in obj[prop]) {
                xml += '<' + prop + '>';
                xml += OBJtoXML(new Object(obj[prop][array]));
                xml += '</' + prop + '>';
            }
        } else {
            xml += '<' + prop + '>';
            typeof obj[prop] == 'object' ? xml += OBJtoXML(new Object(obj[prop])) : xml += obj[prop];
            xml += '</' + prop + '>';
        }
    }
    var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
    return xml;
}
zte4gxcn

zte4gxcn6#

function OBJtoXML(obj, index) {
    var xml = '', 
        root, 
        count = 0;
    if (index > 0) count = index;
    for (var prop in obj) {
      switch (typeof obj[prop]) {
          case 'object': {
              if(obj[prop] instanceof Array) {
                  for (var instance in obj[prop]) {
                    xml += `\n\t<${prop}>\n${OBJtoXML(new Object(obj[prop][instance]))}\t</${prop}>`;
                  }
              }
              else {
                  if (count === 0) {
                    // console.log(`Setting root: ${prop}`)
                    root = prop
                  }
                  xml += `<${prop}>${OBJtoXML(new Object(obj[prop]), count)}\n</${prop}>\n`;
              }
              break;
          }
          case 'number':
          case 'string': {
              // console.log(`Setting ${typeof obj[prop]}`)
              xml += `\t\t<${prop}>${obj[prop]}</${prop}>\n`;
              break;
          }
      }
      count += 1;
    }
    return xml
}

var InputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
var output = eval("OBJtoXML("+InputJSON+");");
console.log(output);
6uxekuva

6uxekuva7#

const objectToXml = (object) => Object.keys(object).reduce((reqStr, key) => {
  const value = object[key] || '';
  const isObject = typeof value === 'object';
  const isArray = Array.isArray(value);
  if (isArray) {
    return reqStr + value.reduce((accumulator, currentValue) =>
      accumulator + `<${key}>${ typeof currentValue === 'object' ? objectToXml(currentValue) : (currentValue || '')}</${key}>`
    ,'');
  }
  if (isObject) {
    return reqStr + `<${key}>${objectToXml(value)}</${key}>`;
  }
  return reqStr + `<${key}>${value}</${key}>`;
}, '');       

const output = objectToXml(yourJson);
console.log(output);
mnemlml8

mnemlml88#

Object/Array到XML转换器

下面的解决方案可以将JS变量转换为(非缩进的)XML字符串。它支持列表(数组)和对象。

  • 使用objectToXml(object)创建具有单个根元素的有效XML。
  • 如果要转换元素数组,请使用variableToXml(variable, 'listElementName')。在本例中,必须将列表元素的标记名称作为第二个参数传递。
function objectToXml(object) {
  if (object instanceof Array || Object.keys(object).length !== 1) {
    throw 'variable has to be an object with a single property'
  }
  return variableToXml(object)
}

function variableToXml(variable, arrayItemPropertyName = null) {
  if (Array.isArray(variable)) {
    return variable.reduce((xml, propertyValue) => {
      const value = variableToXml(propertyValue)
      return `${xml}<${arrayItemPropertyName}>${value}</${arrayItemPropertyName}>`
    }, '')
  }
  if (variable instanceof Object) {
    return Object.entries(variable).reduce((xml, [propertyName, propertyValue]) => {
      const value = variableToXml(propertyValue, propertyName )
      const tag = propertyValue instanceof Array ? value : `<${propertyName}>${value}</${propertyName}>`
      return `${xml}${tag}`
    }, '')
  }
  return variable
}

输入变量

const object = {
  rootTag: {
    intProperty: 4,
    stringProperty: 'foo',
    listOfElements: {
      element: [{
        intProperty: 5,
        stringProperty: 'bar',
      }, {
        intProperty: 5,
        stringProperty: 'bar',
      }],
    },
    list: {
      listElement: [1, 2, 3],
    },
  },
}

输出XML(美化)

<rootTag>
  <intProperty>4</intProperty>
  <stringProperty>foo</stringProperty>
  <listOfElements>
    <element>
      <intProperty>5</intProperty>
      <stringProperty>bar</stringProperty>
    </element>
    <element>
      <intProperty>5</intProperty>
      <stringProperty>bar</stringProperty>
    </element>
  </listOfElements>
  <list>
    <listElement>1</listElement>
    <listElement>2</listElement>
    <listElement>3</listElement>
  </list>
</rootTag>

Demo

const object = {
  rootTag: {
    intProperty: 4,
    stringProperty: 'foo',
    listOfElements: {
      element: [{
        intProperty: 5,
        stringProperty: 'bar',
      }, {
        intProperty: 5,
        stringProperty: 'bar',
      }],
    },
    list: {
      listElement: [1, 2, 3],
    },
  },
}

console.log(objectToXml(object))

function objectToXml(object) {
  if (object instanceof Array || Object.keys(object).length !== 1) {
    throw 'variable has to be an object with a single property'
  }
  return variableToXml(object)
}

function variableToXml(variable, arrayItemPropertyName = null) {
  if (Array.isArray(variable)) {
    return variable.reduce((xml, propertyValue) => {
      const value = variableToXml(propertyValue)
      return `${xml}<${arrayItemPropertyName}>${value}</${arrayItemPropertyName}>`
    }, '')
  }
  if (variable instanceof Object) {
    return Object.entries(variable).reduce((xml, [propertyName, propertyValue]) => {
      const value = variableToXml(propertyValue, propertyName )
      const tag = propertyValue instanceof Array ? value : `<${propertyName}>${value}</${propertyName}>`
      return `${xml}${tag}`
    }, '')
  }
  return variable
}

相关问题