首页 > 解决方案 > 如何解析换行符分隔的 JSON

问题描述

我正在使用 App ScriptsJSON从 GCS 存储桶中提取文件。数据存储为换行符分隔JSON。它作为一个大对象到达,这使得对内部数据的编程访问变得不可能。

我的目标是用 . 分隔每个元素merchant_id。我尝试使用\n作为参数来拆分数据。但是我很难将对象转换为字符串并再次返回。调用JSON.parse响应给了我错误Unexpected token { in JSON at position 1766。虽然这确实将 中的每个元素分开,但单独JSON调用JSON.parse每个元素会给我一个Unexpected end of JSON input错误。

功能

function myFunction() {

let url = 'url_address';
let storedData = [];
let response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
let str = response.toString();
let storedResponse = str.split("\n");

storedResponse.forEach((data) => {
   storedData.push(JSON.parse(data));
});
}

dataforEach 中的示例

{"product_data_timestamp":"2021-05-06 UTC","product_id":"product_id_here","merchant_id":"merchant_id_here","aggregator_id":"agg_id_here","offer_id":"offer_id_here","title":"furniture","description":"description","link":"link","additional_image_links":[],"content_language":"en","target_country":"GB","channel":"online","google_expiration_date":"2021-05-31 22:00:27.517 UTC","availability":"in stock","brand":"brand","color":"black","condition":"new","custom_labels":{"label_0":"GBP"},"item_group_id":"id","mpn":"mpn_id","price":{"value":"129.99","currency":"GBP"},"google_product_category_ids":[],"product_type":"headboards","additional_product_types":[],"destinations":[{"name":"Shopping","status":"approved"}],"issues":[]}

标签: javascriptjsongoogle-apps-script

解决方案


UrlFetchApp.fetch()会给你一个HTTPResponse对象而不是一个 JSON 字符串。您将需要像这样获取响应的内容

  const response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  const str = response.getContentText();
  const jsonObj = JSON.parse(str);

推荐阅读