Safely turning a JSON string into an object
Given a string of JSON data, how can you safely turn that string into a JavaScript object?
Obviously you can do this unsafely with something like...
var obj = eval("(" + json + ')');
...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.
JSON.parse(jsonString)
是一种纯粹的JavaScript方法,只要你能保证一个合理的现代浏览器。
The jQuery method is now deprecated. Use this method instead:
let jsonObject = JSON.parse(jsonString);
Original answer using deprecated jQuery functionality:
If you're using jQuery just use:
jQuery.parseJSON( jsonString );
It's exactly what you're looking for (see the jQuery documentation).
Edit: This answer is outdated and Jonathan's answer above ( JSON.parse(jsonString)
) is now the best answer.
JSON.org has JSON parsers for many languages including 4 different ones for Javascript. I believe most people would consider json2.js their goto implementation.
链接地址: http://www.djcxy.com/p/836.html上一篇: 查看未压入的Git提交
下一篇: 安全地将JSON字符串转换为对象