【发布时间】:2020-04-07 12:04:20
【问题描述】:
如果下面的值是一个字符串,它是一个有效的 JSON。
"{ "key":"value" }"
如果是,在构建 rest api 时,响应 Content-Type 应该是 application/JSON 还是 text/plain ?
【问题讨论】:
如果下面的值是一个字符串,它是一个有效的 JSON。
"{ "key":"value" }"
如果是,在构建 rest api 时,响应 Content-Type 应该是 application/JSON 还是 text/plain ?
【问题讨论】:
不,这不是有效的 JSON,因为字符串中的双引号没有转义。
这是有效的 JSON,它描述了一个具有单个属性的对象:
{ "key":"value" }
这也是有效的 JSON,它描述了一个字符串(它恰好包含一个对象的 JSON):
"{ \"key\":\"value\" }"
现场示例:
console.log(typeof JSON.parse(document.getElementById("obj").value));
console.log(typeof JSON.parse(document.getElementById("str").value));
<!-- This is a convenient way to avoid the issue with escaping the backslash in a string or template literal, which would otherwise obscure the point... -->
<input type="hidden" id="obj" value='{ "key":"value" }'>
<input type="hidden" id="str" value='"{ \"key\":\"value\" }"'>
在构建rest api时,响应Content-Type应该是application/JSON还是text/plain?
应该是application/json(但我认为大小写并不重要)。
【讨论】: