JSON Bool&Number无引号

2,186 阅读1分钟

1.注意

和后端一起定义API时需要注意JSON格式:number和bool是没有引号的。 (今天就因为后端给的API返回了一个字符串"true",导致前端犯了一个低级错误。 后端给的json是{ "feature-B": "true", "feature-A": "false"} json.parse()后得到一个字符串"true/false",通过!!"false" 强制转换得到的值仍为true,意义混乱导致错误)

 let featureEnabled = !!this.store[toggleName];

2.注意:

JSON中的数字类型和Bool类型 是不能放在双引号里面的,否则就成字符串类型了。

let myObj = { name: "John", age: 31, city: "New York" ,flag:true};
let myJSON = JSON.stringify(myObj);
console.log(myJSON);

// result.json :
{
  "name": "John",
  "age": 31,
  "city": "New York",
  "flag": true
}