2012-06-29 52 views
17

我想轉換成設定爲csv格式的JavaScript對象JSON對象轉換爲CSV格式在JavaScript

你可以得到的想法生根粉我的Javascript對象,如果你把它放在網上JSON解析器http://json.parser.online.fr/

這是我想WRK出來... BT就以失敗告終.. http://jsfiddle.net/fHQzC/11/

我試圖採取相應值「術語」和相應的稱號全值到CSV格式

的期待把對像

Time,Dec 9, 2012 
News,Germany,election, Egypt,Revolution, Japan, Earthquake 
Person,Obama, Beckham 
Title,Pearce Snubs Beckham         
Time,Dec 5, Birthday 
Person, Lebron James 
News,Italy,Euro 2012 Final 

標題,熱火的全國冠軍

,並有可能下載Excel工作表的csv文件我棧發現之一是NT真正有用的...

+0

我想你已經檢查http://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel,但這並沒有爲你工作? – Ando

+0

是的,我有...... BT它確實NT .. – user1371896

回答

18

你可以嘗試作爲

$(document).ready(function() { 

     // Create Object 
     var items = [ 
       { name: "Item 1", color: "Green", size: "X-Large" }, 
       { name: "Item 2", color: "Green", size: "X-Large" }, 
       { name: "Item 3", color: "Green", size: "X-Large" }]; 

     // Convert Object to JSON 
     var jsonObject = JSON.stringify(items); 

     // Display JSON 
     $('#json').text(jsonObject); 

     // Convert JSON to CSV & Display CSV 
     $('#csv').text(ConvertToCSV(jsonObject)); 
    }); 

和功能ConvertToCSV

// JSON to CSV Converter 
     function ConvertToCSV(objArray) { 
      var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; 
      var str = ''; 

      for (var i = 0; i < array.length; i++) { 
       var line = ''; 
       for (var index in array[i]) { 
        if (line != '') line += ',' 

        line += array[i][index]; 
       } 

       str += line + '\r\n'; 
      } 

      return str; 
     } 

Source

+0

我的JSON是比這更復雜一點.. – user1371896

+1

複雜性,不影響以此爲CSV將始終保持相同的格式.. –

+0

香港專業教育學院已經嘗試過這一個...我早前在堆棧中發現了這一個.. – user1371896

1

這是我的溶液

https://jsfiddle.net/dhou6y3o/

function iterateObject(obj) { 
    var value = '', header = ''; 
      for (name in obj) { 
      if (obj.hasOwnProperty(name)) { 
       if (isObject(obj[name])) { 
       var out = iterateObject(obj[name]); 
       value += out.value; 
       header += out.header; 
       } else { 
       value += removeNewLine(obj[name]) + '; '; 
       header += name + '; '; 
       } 
      } 
      } 
    return { 
    "value":value, 
    "header":header 
    }; 
} 
function isObject(obj) { 
    return (typeof obj === 'object'); 
} 
function removeNewLine(item) { 
    return item.toString().replace(/(\r\n|\n|\r)/gm,""); 
} 
1

這是我的溶液

function arrayToCSV(objArray) { 
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray; 
    let str = `${Object.keys(array[0]).map(value => `"${value}"`).join(",")}` + '\r\n'; 

    return array.reduce((str, next) => { 
     str += `${Object.values(next).map(value => `"${value}"`).join(",")}` + '\r\n'; 
     return str; 
     }, str); 
} 

實施例:

let arr = [{name: "Essa", age: 25}]; 
console.log(arrayToCSV(arr));