外观风格
JSON 安全操作
使用安全的 JSON 解析方式
- 应使用 JSON.parse() 解析JSON字符串。低版本浏览器,应使用安全的 Polyfill 封装。
// bad: 直接调用eval解析json
const sUserInput = getURLParam("json_val");
const jsonstr1 = `{"name":"a","company":"b","value":"${sUserInput}"}`;
const json1 = eval(`(${jsonstr1})`);
// good: 使用JSON.parse解析
const sUserInput = getURLParam("json_val");
JSON.parse(sUserInput, (k, v) => {
if (k === "") return v;
return v * 2;
});
// good: 低版本浏览器,使用安全的Polyfill封装(基于eval)
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>;
const sUserInput = getURLParam("json_val");
JSON.parse(sUserInput);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16