在javascript,打字稿中将json转换为csv

Posted

技术标签:

【中文标题】在javascript,打字稿中将json转换为csv【英文标题】:Converting json to csv in javascript, typescript 【发布时间】:2020-07-15 14:44:42 【问题描述】:

您好,我正在尝试将一些 json 转换为 cvs,但我没有运气解析它,我找到了一些看起来像这样的简单 json 的解决方案

json =  [
    
      name: "Anil Singh",
      age: 33,
      average: 98,
      approved: true,
      description: "I am active blogger and Author."
    ,
    
      name: 'Reena Singh',
      age: 28,
      average: 99,
      approved: true,
      description: "I am active HR."
    ,
    
      name: 'Aradhya',
      age: 4,
      average: 99,
      approved: true,
      description: "I am engle."
    ,
  ];

我有这样的方法

convertToCSV(objArray, headerList): string 
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = 'S.No,';
    // tslint:disable-next-line: forin
    for (const index in headerList) 
      row += headerList[index] + ',';
    
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) 
      let line = (i + 1) + '';
      // tslint:disable-next-line: forin
      for (const index in headerList) 
        const head = headerList[index];
        line += ',' + array[i][head];
      
      str += line + '\r\n';
    
    return str;
  

然后这样称呼它

const csvData = this.convertToCSV(json, ['name', 'age', 'average', 'approved', 'description']);

一个看起来像这样的复杂对象的问题

json = [
        "customer": 
            "emailAddress": "test@gmail.com"
        ,
        "recommendationProductDetails": [
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        , 
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        ]
    ,
    
        "customer": 
            "emailAddress": "test33@gmail.com"
        ,
        "recommendationProductDetails": [
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        , 
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        ]
    
];

有人可以帮忙在 cvs 中格式化这个 json,谢谢

【问题讨论】:

你的 json 数组中的所有对象都相关吗?使用 json.filter( obj => obj.name) 来获取所有有名字的东西。使用 json.filter( obj => obj.name ).map( obj => obj.name + "," + obj.age) 在过滤后的对象上获取 csv,其中包含名称、年龄。如果我是你,我会将数据粘贴到 chrome 控制台中,然后在那里使用代码 - 更快地找到解决方案 你能回答一下吗,谢谢 我们需要一个您想要的输出示例。复杂的嵌套 JSON 对象不能简单地以平面 CSV 格式表示。您希望您的 CSV 看起来像什么? 如果我这样做:[].concat.apply([], json.map(j =&gt; j.recommendationProductDetails.map(c =&gt; j.customer.emailAddress + "," + c.productId + "," + c.title + "\n"))) 给你上面的数据 - 我得到一个 CSV 数组 - 但我不确定你想要什么 - 希望它有所帮助 另外 - 您需要在描述字段中处理特殊字符 - 对于逗号,我会在这些字段周围加上引号,在您的 csv 输出中 - 但您可能还需要检查引号和逗号等。在数据中的描述字段中,并决定如何处理这些 【参考方案1】:

将此类复杂对象转换为 CSV 有一些解决方法

希望下面的代码会有所帮助

var jsondata = [
        "customer": 
            "emailAddress": "test@gmail.com"
        ,
        "recommendationProductDetails": [
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        , 
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        ]
    ,
    
        "customer": 
            "emailAddress": "test33@gmail.com"
        ,
        "recommendationProductDetails": [
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        , 
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        ]
    
];



function flattenObjectKeys(ob) 
    var toReturn = ;

    for (var i in ob) 
        if (!ob.hasOwnProperty(i)) continue;

        if ((typeof ob[i]) == 'object' && ob[i] !== null) 
            var flatObject = flattenObjectKeys(ob[i]);
            for (var x in flatObject) 
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            
         else 
            toReturn[i] = ob[i];
        
    
    return toReturn;


function transformToCSV(jsondata, keysArr=[])

    var csvData = "";
    var itemList = [];
    jsondata.forEach(customer=>
        itemList.push(flattenObjectKeys(customer));
    )
    var newKeysNames = Object.keys(itemList[0]);
    var keysMap = ;
    newKeysNames.forEach(newKeyName => 
        keysArr.forEach((oldKeyName)=>
            let findName = "."+ oldKeyName;
            if( String(newKeyName).indexOf(findName) >= 0)
            

                keysMap[oldKeyName] = newKeyName;
            
        )
    );
   // console.log("Keys Map === ", keysMap);
    itemList.forEach((item)=>
        keysArr.forEach(keyName=>
            csvData+=item[keysMap[keyName]] +",";
        )
        csvData+='\r\n';
    )


    return csvData;



console.log("====================");
console.log(transformToCSV(jsondata, ['title','webAddress','description']));
console.log("====================");

【讨论】:

以上是关于在javascript,打字稿中将json转换为csv的主要内容,如果未能解决你的问题,请参考以下文章

在Angular8中将HTTP响应json转换为打字稿对象

在javascript中将数字转换为数组| angular7的打字稿[重复]

如何在打字稿接口/类型中将枚举值类型转换为数组?

如何在打字稿中将存储在 Observable<any> 中的值转换为字符串?

打字稿将数组转换为 JSON

将firebase json转换为打字稿数组