Skip to content

Read In JSON From File And DONT Eval

fabiantheblind edited this page Nov 19, 2015 · 2 revisions

Eval is Evil. Improper use of eval opens up your code for injection attacks. http://stackoverflow.com/a/86580

As the title says. There is a better way to import json from file. got to https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json2.js and download the file to your hard drive next to your executing script. Also create a file called "JSONString.json" at the same location. The content can be something like this.

{"arr":[0,0,0,0],"str":"something"}   
    #include "json2.js" // jshint ignore:line
    var script_file = File($.fileName); // get the location of the script file
    var script_file_path = script_file.path; // get the path

    var file_to_read = File(script_file_path + "/JSONString.json");// but we want JSON
    var my_JSON_object = null; // create an empty variable
    //  alert(file_to_read); // This could be interesting
    var content; // this will hold the String content from the file
    if(file_to_read !== false){// if it is really there
          file_to_read.open('r'); // open it
          content = file_to_read.read(); // read it
          my_JSON_object =  JSON.parse(content);// now evaluate the string from the file
          alert(my_JSON_object.toSource()); // if it all went fine we have now a JSON Object instead of a string call length
          file_to_read.close(); // always close files after reading
          }else{
          alert("Bah!"); // if something went wrong
    }
Clone this wiki locally