【问题标题】:Is a JSON value in double quote a valid JSON?双引号中的 JSON 值是有效的 JSON 吗?
【发布时间】:2020-04-07 12:04:20
【问题描述】:

如果下面的值是一个字符串,它是一个有效的 JSON。

"{ "key":"value" }"

如果是,在构建 rest api 时,响应 Content-Type 应该是 application/JSON 还是 text/plain ?

【问题讨论】:

    标签: json rest api


    【解决方案1】:

    不,这不是有效的 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(但我认为大小写并不重要)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-28
      • 2011-05-08
      • 2018-01-07
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多