为什么别人家返回的 json 字符串是自带格式化效果的, 而我的就是一坨长串?

2016-06-27 10:45:17 +08:00
 chineselittleboy

这是别人家的:

这是我家的:

7763 次点击
所在节点    问与答
45 条回复
miaosu
2016-06-27 16:03:17 +08:00
这个无所谓吧。。。我觉得你的更好一些~
pi1ot
2016-06-27 16:06:42 +08:00
你返回的 http head 里的 content-type 不是 json
zencoding
2016-06-27 16:10:28 +08:00
header("Content-Type: application/json;")
gyteng
2016-06-27 16:18:23 +08:00
显然是一坨好, pretty 的话涉及用 tab 还是 space ,会引起圣战的。
BOYPT
2016-06-27 16:26:27 +08:00
一般 jsonnify 函数都有 pretty 开关的,比如 php 的 json_encode($data, JSON_PRETTY_PRINT);
比如 nodejs 的 JSON.stringify(data, null, 4);

在程序看来是等效的(非压缩传输的话会带了比较多空格)
ipconfiger
2016-06-27 16:35:50 +08:00
就一串, 省流量. format 的话到本地了用工具
Vie
2016-06-27 16:42:38 +08:00
<div class="box">
<div class="inner" align="center">
<a href="https://www.wilddog.com/?utm_source=v2ex&amp;utm_medium=banner&amp;utm_content=homepageright&amp;utm_campaign=suzhoucodingcamp" target="_blank"><img src="//cdn.wilddog.com/images/ads/v2ex/v2ex-500x500-1.jpg" border="0" width="250" height="250" alt="野狗科技"></a>
</div>
</div>
Vie
2016-06-27 16:42:55 +08:00
@Vie 竟然不行
binux
2016-06-27 16:47:10 +08:00
@incompatible
1. 难道不加 indent 就不开 gzip 了吗?
2. 就算内部不 gzip ,多几个空格能大多少,有多少影响。真在意 protobuf 啊, msgpack 都好过 JSON 。
3. 会增加,但是并不会增加多少。 pretty 不是额外操作,是序列化的内部过程,只是是否在输出 object 序列化前判断下是否加入 indent ,并不会增加多少消耗。

这东西难道不是纯看喜好吗?
jswh
2016-06-27 17:01:48 +08:00
@binux @incompatible
PHP7 的 json 函数解析其中有控制符的 json 的时候会出错,无法正确解析。官方回复是不会支持,因为 json 的标准里面就是没有控制符的。我没有读过标准,不知真假。
这个坑了我很久。
binux
2016-06-27 17:14:15 +08:00
@jswh 什么叫有控制符的 json ? JSON 标准规定:

> All Unicode characters may be placed within the
> quotation marks, except for the characters that must be escaped:
> quotation mark, reverse solidus, and the control characters (U+0000
> through U+001F).

有控制符的 json 那还叫 json 吗?
jswh
2016-06-27 17:17:21 +08:00
@binux 就是那些为了格式化而放的换号, tab 之类的
binux
2016-06-27 17:20:21 +08:00
@jswh 瞎说

JSON-text = ws value ws

Insignificant whitespace is allowed before or after any of the six
structural characters.

ws = *(
%x20 / ; Space
%x09 / ; Horizontal tab
%x0A / ; Line feed or New line
%x0D ) ; Carriage return
zarvin
2016-06-27 17:25:40 +08:00
chrome 的话可以用 web 前端助手 这个插件
Lullaby
2016-06-27 21:34:51 +08:00
jsonview
kslr
2016-06-27 22:42:41 +08:00
@pi1ot 你是图钉吗
fhefh
2016-06-27 22:45:16 +08:00
kevinroot
2016-06-27 23:05:34 +08:00
“别人家的”多了一些空格换行,浪费空间。就是应该一坨,解析或者用工具查看就好了。 chrome 有 JSONView
predator
2016-06-27 23:13:16 +08:00
我家开发测试环境带 PRETTY 格式,生产环境不带
lslqtz
2016-06-27 23:34:39 +08:00
@slixurd 那么小数据没必要开 gzip 。。
个人表示,不喜欢加空格,这些是让程序来处理的。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/288532

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX