javascript - 如何解析换行符分隔的 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));
});
}
data
forEach 中的示例
{"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":[]}
解决方案
UrlFetchApp.fetch()
会给你一个HTTPResponse对象而不是一个 JSON 字符串。您将需要像这样获取响应的内容:
const response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
const str = response.getContentText();
const jsonObj = JSON.parse(str);
推荐阅读
- asp.net - 如何访问实体框架外键对象
- command-line - P4 如何将文件签出到指定更改列表?(使用命令行)
- tomcat - HTTP 状态 500 – 在 tomcat 中部署 war 文件时出现内部服务器错误
- c++ - 如何正确地为 ncurses 进行 epoll
- file - 无法通过 CStdioFile 将中文字符写入 ANSI 文件?
- regex - 获取字符串的中间字符
- visual-studio-code - 在“Visual Studio Code”中按类型对文件进行分组并按日期排序
- php - PhpStorm 无法添加 CLI 解释器
- java - 如何处理列表整数列表并查找邻居?
- node.js - 为什么在 NodeJS 中使用“require”时会出现如此奇怪的行为?