I am trying to read a JSON file, in order to make changes in an illustrator document according to the data in that JSON file.
I tried this code:
#include 'libs/json2.js';
function readJSONFile(file) {
file.open("r");
var data = file.read();
file.close();
data = JSON.parse(data);
for(var i in data) {
$.writeln(i + "=" + data[i]);
}
}
function getCorrections()
{
const corrections = readJSONFile(File('C:/corrections.json'));
alert(corrections);
}
getCorrections();
but when I run the script in Illustrator, it gives me an error saying "JSON is undefined"
so, I tried to use #import
as I've seen in other Stackoverflow threads, but it seems like Illustrator don't accept that syntax.
#include 'libs/json2.js';
I get this error:
Error 23: ) does not not have a value.
Line: 1
-> ()
I would be glad to get some help importing an external library to my script, thank you.
Try this:
// @include 'libs/json2.js'
But actually both of the variants work for me. #include
is a valid option for Illustrator.
Perhaps the problem is in your data. I could try to parse it if you provide the sample of your date.
Here is full code that works for me:
#include 'libs/json2.js';
var file = File('d:/stackoverflow/jsx/json/test.json'); // <-- a full path!!!
readJSONFile(file);
function readJSONFile(file) {
file.open("r");
var data = file.read();
file.close();
data = JSON.parse(data);
for (var i in data) {
$.writeln(i + "=" + data[i]);
}
}
test.json
file:
{
"patches": [
{
"patchName": "N0",
"offsetL": "1",
"offsetA": "-1",
"offsetB": "2"
},
{
"patchName": "N1",
"offsetL": "1",
"offsetA": "-1",
"offsetB": "2"
}
]
}
Everything works fine:
Check the path to your json file.
You can get the folder that contains a current script this way:
var script_folder = File($.fileName).parent;
alert(script_folder); // 'd/stackoverflow/jsx/json' in my case