【问题标题】:How can I read a stream of JSON objects into browser如何将 JSON 对象流读入浏览器
【发布时间】:2017-03-06 07:17:39
【问题描述】:
给定一个node.js样式的对象流,如下例所示,网页上的http请求如何读取并处理它:
{"id":"one", "value":"the first object"}
{"id":"two", "value":"the second object"}
{"id":"three", "value":"the third object"}
【问题讨论】:
标签:
jquery
node.js
node.js-stream
highland.js
oboe.js
【解决方案1】:
渐进式解析 http 请求是 oboe.js 的优点。您要发送的内容似乎称为 JSON Lines。从技术上讲,oboe 仅支持接收单个有效的 JSON 对象或数组。但我发现你可以让它为你的数据工作:)
oboe('/data.json')
.node('{id value}', function(x) {
console.log('object', x)
})
.node('!', function(x) {
console.log('root', x)
})
您可以使用oboe 来请求加载数据(它在后台使用本机 XMLHttpRequest)。然后使用node 为同时具有id 属性和values 属性的任何对象或具有! 的任何根级对象添加侦听器。请注意,您不必同时使用两者。
您可以查看工作示例here 和源代码here。
问题:如果您尝试使用双簧管的done 函数,需要注意的一点是它会触发多次,每个对象触发一次。那是因为每个都会被解析为一个完整的有效对象。