从Shopify API中,我收到了一个指向大量JSONL的链接。使用NodeJS,我需要逐行读取这个数据,因为一次加载会占用大量内存。当我从web浏览器点击JSONL url时,它会自动将JSONL文件下载到我的下载文件夹。
JSONL的例子:
{"id":"gid:\/\/shopify\/Customer\/6478758936817","firstName":"Joe"}
{"id":"gid:\/\/shopify\/Order\/5044232028401","name":"#1001","createdAt":"2022-09-16T16:30:50Z","__parentId":"gid:\/\/shopify\/Customer\/6478758936817"}
{"id":"gid:\/\/shopify\/Order\/5044244480241","name":"#1003","createdAt":"2022-09-16T16:37:27Z","__parentId":"gid:\/\/shopify\/Customer\/6478758936817"}
{"id":"gid:\/\/shopify\/Order\/5057425703153","name":"#1006","createdAt":"2022-09-27T17:24:39Z","__parentId":"gid:\/\/shopify\/Customer\/6478758936817"}
{"id":"gid:\/\/shopify\/Customer\/6478771093745","firstName":"John"}
{"id":"gid:\/\/shopify\/Customer\/6478771126513","firstName":"Jane"}
我不知道如何在NodeJS中处理这些数据。我是否需要点击url,下载所有数据并将其存储在一个临时文件中,然后逐行处理数据?或者,在访问url (通过某种流)之后,我可以逐行读取数据吗?并处理它而不将其存储在服务器上的临时文件中?
( JSONL来自https://storage.googleapis.com/,如果这有帮助的话。)
谢谢。
发布于 2022-10-07 21:09:12
使用axios
,您可以将响应设置为stream
,然后使用buildin readline模块,您可以逐行处理数据。
import axios from 'axios'
import { createInterface } from 'node:readline'
const response = await axios.get('https://raw.githubusercontent.com/zaibacu/thesaurus/master/en_thesaurus.jsonl', {
responseType: 'stream'
})
const rl = createInterface({
input: response.data
})
for await (const line of rl) {
// do something with the current line
const { word, synonyms } = JSON.parse(line)
console.log('word, synonyms: ', word, synonyms);
}
对此进行测试,几乎没有内存使用。
发布于 2022-10-08 00:34:10
您可以轻松地运行一个名为jq的出色的CLI工具。魔术。
与将自己绑定到浏览器代码不同,此代码可以以任何需要解析JSONL的方式运行。
jq -cs '.' doodoo.myshopify.com.export.jsonl > out.json
将使用我刚刚从查询中下载的大容量文件,并为我提供一个非常好的纯JSON数据结构,以供使用或保存。
https://stackoverflow.com/questions/73991260
复制相似问题