JSON to XML Using Javascript

前端 未结 6 944
南旧
南旧 2020-12-11 09:25

I am trying to convert the JSON to XML but not getting exact output.In My JSON having array object it not converting that to XML array.Mainly array object is not converti

6条回答
  •  萌比男神i
    2020-12-11 10:11

    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 || '')}`
        ,'');
      }
      if (isObject) {
        return reqStr + `<${key}>${objectToXml(value)}`;
      }
      return reqStr + `<${key}>${value}`;
    }, '');       
    
    const output = objectToXml(yourJson);
    console.log(output);
    

提交回复
热议问题