渐进式 JSON — 过度反应

May 31, 2025

2025年5月31日

Do you know about Progressive JPEGs? Here’s a nice explanation of what a Progressive JPEG is. The idea is that instead of loading the image top to bottom, the image instead is fuzzy at first and then progressively becomes more crisp.

你知道渐进式 JPEG 吗?这里有一个很好的解释关于什么是渐进式 JPEG。这个想法是,图像不是从上到下加载,而是最开始模糊,然后逐渐变得更加清晰。

What if we apply the same idea to transferring JSON?

如果我们将同样的想法应用于传输 JSON 呢?

Suppose you have a JSON tree with some data:

假设你有一个包含一些数据的JSON树:

{
 header: 'Welcome to my blog',
 post: {
 content: 'This is my article',
 comments: [
 'First comment',
 'Second comment',
 // ...
 ]
 },
 footer: 'Hope you like it'
}

Now imagine you want to transfer it over the wire. Because the format is JSON, you’re not going to have a valid object tree until the last byte loads. You have to wait for the entire thing to load, then call JSON.parse, and then process it.

现在想象一下你想通过网络传输它。因为格式是 JSON,直到最后一个字节加载完成之前,你不会有一个有效的对象树。你必须等到整个内容加载完成,然后调用JSON.parse,再进行处理。

The client can’t do anything with JSON until the server sends the last byte. If a part of the JSON was slow to generate on the server (e.g. loading comments took a slow database trip), the client can’t start any work until the server finishes all the work.

在服务器发送 最后 一个字节之前,客户端无法对 JSON 做 任何 操作。如果 JSON 的某部分在服务器上生成缓慢(例如,加载 comments 需要慢速数据库访问),客户端无法 开始任何 工作,直到服务器 完成所有 工作。

Would you call that good engineering? And yet it’s the status quo—that’s how 99.9999%* of apps send and process JSON. Do we dare to improve on that?

你会称这为良好的工程吗?然而这就是现状——99.9999%* 的应用程序都是这样发送和处理 JSON 的。我们敢于改进吗?

* I made it up

* 我是随便说的

Streaming JSON

流式 JSON

We can try to improve this by implementing a streaming JSON parser. A streaming JSON parser would be able to produce an object tree from an incomplete input:

我们可以通过实现一个流式 JSON 解析器来尝试改善这一点。流式 JSON 解析器能够从不完整的输入中生成对象树:

{
 header: 'Welcome to my blog',
 post: {
 content: 'This is my article',
 comments: [
 'First comment',
 'Second comment'

If you ask for the result at this point, a streaming parser would hand you this:

如果你在这个时候请求结果,流式解析器将会交给你这个:

{
...
开通本站会员,查看完整译文。

ホーム - Wiki
Copyright © 2011-2025 iteam. Current version is 2.144.0. UTC+08:00, 2025-06-06 19:08
浙ICP备14020137号-1 $お客様$