【问题标题】:How to correctly structure json and configure json2csv to output correct columns and rows?如何正确构造 json 并配置 json2csv 以输出正确的列和行?
【发布时间】:2020-08-05 22:18:07
【问题描述】:

数据以这种形状开始:

   [
      {
        date: "July 5, 2020"
        name: "Calories"
        symbol: "CALORIES"
        value: 1,545.2
        ..,
      },
      {
        date: "July 7, 2020"
        name: "Total Carbs (g)"
        symbol: "TOTAL_CARBS"
        units: "g"
        value: 45.2
        ..,
      },
      ...
    ]

输出的.csv 文件的预期形状应为:

    ---------------   2020-07-05  2020-07-07   ...
    Calories          1,545.2     1,6276.3     ...
    Total Carbs (g)   45.2        56.9         ...
    ...

在传递给解析函数之前我应该​​如何转换数据?类似于:

const transformedQueryData = [
      {
        'date': 2020-07-05,
        'CALORIES': 1,545.2,
        'TOTAL_CARBS': 45.2,
      },
      {
        'date': 2020-07-07,
        'CALORIES': 1,6276.3,
        'TOTAL_CARBS': 56.9,
      }
    ];

    OR

    const transformedQueryData = [
      {
        2020-07-05: {
          'CALORIES': 1,545.2,
          'TOTAL_CARBS': 45.2,
        }
      },
      {
        2020-07-07: {
          'CALORIES': 1,6276.3,
          'TOTAL_CARBS': 56.9,
        }
      }
    ];

或者我可以使用 json2csv 实用程序和配置来按原样处理 queriedData 吗?

【问题讨论】:

  • 不是 .csv 是 .tsv 格式。

标签: javascript json csv transformation json2csv


【解决方案1】:

我创建了一个函数,将日期值拆分为 3 个元素:月、日、年,然后将日期值替换为自定义的。

var ex = [
      {
        "date": "July 5, 2020",
        "name": "Calories",
        "symbol": "CALORIES",
        "value": "1,545.2"
      },
      {
        "date": "July 7, 2020",
        "name": "Total Carbs (g)",
        "symbol": "TOTAL_CARBS",
        "units": "g",
        "value": 45.2
      }
    ];

function getMonth(val){
  switch(val){
    case "January": return 1; break;
    case "February": return 2; break;
    case "March": return 3; break;
    case "April": return 4; break;
    case "May": return 5; break;
    case "June": return 6; break;
    case "July": return 7; break;
    case "August": return 8; break;
    case "Semptember": return 9; break;
    case "Octomber": return 10; break;
    case "November": return 11; break;
    case "December": return 12; break;
  }
     
}

//iterates for each subarray of json array
ex.forEach(function(record) {
    if (record.date != null) {
        let temp = record.date.replace(',',''); //remove ',' from string
        let arr = temp.split(" "); //split to month,day,year
        
        let month = getMonth(arr[0]);
        let day = arr[1].length == 2 ? arr[1] : '0'+arr[1]; //add 0 in front if day has one digit

        let strBuilder = arr[2]+"-"+day+"-"+month; //concatenate the values

        record.date = strBuilder; //replace the date value with the custom one

    }
});

console.log(ex);

我认为这会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多