1

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 isn't malicious.

What is a good way to do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
static_rtti
  • 53,760
  • 47
  • 136
  • 192
  • As long as you don't attempt to execute anything during validation it should be fine. Don't use code execution to test for validity (i.e. if it runs, it's valid; otherwise no). – BoltClock Mar 19 '11 at 22:09
  • 2
    just use json2.js http://www.json.org – KJYe.Name Mar 20 '11 at 00:10

2 Answers2

2

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.

Community
  • 1
  • 1
Travis Webb
  • 14,688
  • 7
  • 55
  • 109
1

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.

rjmunro
  • 27,203
  • 20
  • 110
  • 132