【问题标题】:Parse Nested Json Data to Google Sheets with App Script使用 App 脚本将嵌套的 Json 数据解析为 Google 表格
【发布时间】:2020-07-07 00:59:03
【问题描述】:

我正在尝试将 JSON 解析为 Google 表格。一切都像一个魅力,除了我发现 JSON 有我需要作为列返回的子项。

Json 示例

{
  "status": "OK",
  "items": [
    {
      "order_id": 1290,
      "date": "2019-12-24",
      "services": [
        {
          "start_at": "08:00",
          "end_at": "09:00",
          "service_id": 121,
          "assistant_id": 0
        }, 
        {
          "start_at": "12:00",
          "end_at": "13:00",
          "service_id": 122,
          "assistant_id": 0
        }
      ],
    }
  ]
}

而我需要进入 Google 表格的是

order_id|date       |services.start_at|services.end_at|services.service_id|services.assistant_id|
1290    |2019-12-24 |08:00            |09:00          |121                |0                    |
1290    |2019-12-24 |12:00            |13:00          |122                |0                    |

我已经尝试过了,但如果多个服务在同一个 order_id 下,我不知道如何获取子项并重复 id 和 date 的值。

   var response = UrlFetchApp.fetch(url, options);
   var object = JSON.parse(response.getContentText());
   var headers = Object.keys(object.items[0]);
   var values = object.items.map(function(e) {return headers.map(function(f) {return e[f]})});
   values.unshift(headers);
   var sheet = SpreadsheetApp.getActiveSheet();
   sheet.getRange(2, 1, values.length, values[0].length).setValues(values);

我希望这里的任何人都可以给我一个线索,因为我已经尝试了几天没有运气,我是 JSON 和在 Apps 脚本中解析东西的菜鸟。

祝你有美好的一天:)

【问题讨论】:

  • 我认为您的“Json Example”示例值可能存在错误。能否再次确认services的属性?
  • 为了简单起见,我只是编辑了json,结果出错了。
  • 感谢您的回复和更新。我注意到已经发布了答案。在这种情况下,我想尊重现有的答案。我认为它会解决您的问题。

标签: javascript json google-apps-script google-sheets


【解决方案1】:

您可能想要创建一个函数,给定一个多级对象,该函数返回一个包含行的平面数组,每个行都有其属性。

注意:因为我不知道是否允许 ES6 语法,所以我使用了更旧、更冗长但更兼容的 ES5 语法(这让我意识到我是多么喜欢 ES6 及其快捷方式!) em>

演示

function buildRows(data) {
  return data.items.reduce(function(res, item) {
    var sharedProps = {}, // item properties
        items       = []; // services

    // For each item [key, value] pair
    Object.entries(item).forEach(function(pair) {
      var key = pair[0],
        value = pair[1];
      // If the value is an Array (services)
      if (value instanceof Array) {
        // Add the item, prefixed with the key ("services")
        [].push.apply(items,
          value.map(function(obj) {
            return Object.fromEntries(
              Object.entries(obj).map(function(pair) {
                return [key + '.' + pair[0], pair[1]]
              })
            );
          })
        );
      } else {
        // Otherwise, add it as a shared property
        sharedProps[key] = value;
      }
    });

    // Add the shared props to each item (service) before adding them
    return res.concat(
      items.map(function(item) {
        return Object.assign({}, sharedProps, item);
      })
    );
  }, []);
}

// For the demo
var object = {"status":"OK","items":[{"order_id":1290,"date":"2019-12-24","services":[{"start_at":"08:00","end_at":"09:00","service_id":121,"assistant_id":0},{"start_at":"12:00","end_at":"13:00","service_id":122,"assistant_id":0}]}]};

// Build the rows
var rows = buildRows(object);
// Get the headers
var headers = Object.keys(rows[0]);
// Get the values
var values = rows.map(function(row) {
  return headers.map(function(header) {
    return row[header];
  });
});
// Do what you need to do to insert them in the Sheet,
// this is just for the demo:
result.innerHTML = headers.join('\t') + '\n'
                 + values.map(function(row) {
                     return row.join('\t\t');
                   }).join('\n');
<pre id="result"></pre>

【讨论】:

  • 谢谢,确实按预期工作。扁平化结果是解决它的关键。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2022-09-25
  • 1970-01-01
  • 2019-10-28
  • 2010-10-22
  • 2023-01-15
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多