【问题标题】:Can I fetch a Readable Stream then convert to JSON client side?我可以获取可读流然后转换为 JSON 客户端吗?
【发布时间】:2018-10-23 13:25:56
【问题描述】:

我希望使用 Google 表格 CSV 作为数据源。我想在客户端获取 CSV 数据,然后转换成 JSON。

我能够获取 CSV,它返回 ReadableStream。但是,我不确定如何正确读取该响应并将其转换为 JSON。

我找到了一个npm package which should help convert the CSV data to JSON,但有一点时间处理流。

例如:https://jsfiddle.net/21jeq1h5/3/

谁能指出我使用ReadableStream的正确方向?

【问题讨论】:

标签: javascript json csv stream


【解决方案1】:

由于 CSV 是简单的文本,解决方案是使用 fetch() API 的 response.text() 方法。

https://developer.mozilla.org/en-US/docs/Web/API/Body/text

文本载入后,就像从文件中解析 CSV 一样简单。如果您希望将对象作为输出,则必须将标头包含在 CSV(您的)中。

我在下面包含了代码 sn-p。它不会在 SO 上运行,因为 SO 在 AJAX 请求上将源设置为 null。因此,我还提供了一个指向有效的 codepen 解决方案的链接。

fetch('https://docs.google.com/spreadsheets/d/e/KEY&single=true&output=csv')
  .then(response => response.text())
  .then(transform);

function transform(str) {
  let data = str.split('\n').map(i=>i.split(','));
  let headers = data.shift();
  let output = data.map(d=>{obj = {};headers.map((h,i)=>obj[headers[i]] = d[i]);return obj;});
  console.log(output);
}

https://codepen.io/randycasburn/pen/xjzzvW?editors=0012

编辑

我应该补充一点,如果你真的想在 JSON 字符串中使用它(根据你的问题),你可以运行

json = JSON.stringify(output);

【讨论】:

  • @vinnie-james 您所建议的内容不会以 ReadableStream 的形式返回响应。 response.text() 将从资源中返回整个文本,而不是以块的形式获取数据。我希望它是您想要的,否则解决方案是错误的。
猜你喜欢
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
相关资源
最近更新 更多