You can use eval()
to achieve an effect similar to JSON.parse()
.
eval('obj = {' + JSONstring + '}');
And afterwards, obj.toString()
will let you retrieve the data similar to JSON.stringify()
(just without the beautify options). See this answer for an example in the wild. The point is, you can create an object from JSON text without having to load any external libraries or switch the interpreter engine.
BIG FAT WARNING!!!
This introduces a vulnerability into the workstation running your code. If you do not control the generation of the JSON you wish to parse, or if it is possible that a 3rd party might modify the JSON between its generation and its interpretation, then consider following Helen's advice. If bad things are in the JSON, it can cause your WScript to do bad things. For example, if your JSON string or 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 have just added a new administrator to your computer without any visual indication that it happened.
My advice is to feel free to employ 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 the JSON methods by invoking the htmlfile
COM object and forcing it into IE9 (or higher) compatibility mode by means of a <META>
tag like this:
var htmlfile = WSH.CreateObject('htmlfile'), JSON;
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
With those three lines, the JSON object and methods are copied into the JScript runtime, letting you parse JSON without using eval()
or downloading json2.js. You can now do stuff 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's 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 (json2.js download via XHR, InternetExplorer.Application
COM object, an HTA hybrid method, and another example of htmlfile
).