开发者

Is there a secure way to validate JSON input with JavaScript?

I am pulling some external JSON data from a Windows 7 Gadget, which is basically a piece of JavaScript running under Internet Explorer with high security priviledges. Because of that, I want to make sure the JSON is properly formatted and i开发者_如何学运维sn't malicious.

What is a good way to do this?


JSON is JavaScript. Therefore, you can validate JSON statically in the same way you would validate JavaScript. You are concerned about the eval approach that can usually be used to validate JavaScript, and you are being very wise to avoid this approach. If it's malicious and you execute to validate, well you're already screwed. JSLint is a great tool for this. See Stack Overflow question Is JSLint available for offline use? for how to utilize this utility "offline".

Another approach is to use json2.js. This method does correctly parse JSON containing functions, so be aware of this caveat.


Use JSON.parse(jsonString);. This will build arrays and objects but not run any code in the JSON. To support older browsers without the HTML5 JSON object, use json2.js which provides the same protection using the same API by checking for invalid data before eval()ing the JSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜