You can use eval() to achieve an effect similar to JSON.parse() .
eval('obj = {' + JSONstring + '}');
And after that, obj.toString() will allow you to get data similar to JSON.stringify() (only without beautify parameters). See this answer for an example in the wild. The fact is that you can create an object from JSON text without having to load any external libraries or switch the interpreter mechanism.
PREVENTION OF THE BIG FOOD !!!
This leads to a vulnerability in the workstation where your code is running. If you are not in control of the JSON generation you want to parse, or if it is possible that a third party can change the JSON between your generation and its interpretation, consider Helen's next tip . If there are bad things in JSON, this can cause your WScript to do bad things. For example, if a line or JSON file contains the following:
}; var oSH = WSH.CreateObject("wscript.shell"), cmd = oSH.Exec("%comspec%"); WSH.Sleep(250); cmd.StdIn.WriteLine("net user pwnd password /add"); WSH.Sleep(250); cmd.StdIn.WriteLine("net group Administrators pwnd /add"); WSH.Sleep(250); cmd.Terminate(); var obj = { "objName": { "item1": "value 1", "item2": "value 2" }
... then parsing it with eval will simply add a new administrator to your computer without any visual indication that this has happened.
My advice: feel free to use eval for private or casual use; but for widespread deployment, consider including json2.js , as Helen suggests. Edit: Or ...
htmlfile COM object
You can import JSON methods by calling the htmlfile COM object and making it work in compatibility mode with IE9 (or higher) using the <META> as follows:
var htmlfile = WSH.CreateObject('htmlfile'), JSON; htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />'); htmlfile.close(JSON = htmlfile.parentWindow.JSON);
With these three lines, the JSON object and methods are copied to the JScript runtime, allowing you to parse JSON without using eval() or loading json2.js. Now you can do things like this:
var pretty = JSON.stringify(JSON.parse(json), null, '\t'); WSH.Echo(pretty);
Here's a breakdown:
// load htmlfile COM object and declare empty JSON object var htmlfile = WSH.CreateObject('htmlfile'), JSON; // force htmlfile to load Chakra engine htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />'); // The following statement is an overloaded compound statement, a code golfing trick. // The "JSON = htmlfile.parentWindow.JSON" statement is executed first, copying the // htmlfile COM object JSON object and methods into "JSON" declared above; then // "htmlfile.close()" ignores its argument and unloads the now unneeded COM object. htmlfile.close(JSON = htmlfile.parentWindow.JSON);
See this answer for other methods (loading json2.js via XHR, InternetExplorer.Application COM object, hybrid HTA method and another htmlfile example).