I'm attempting to read JSON from a configuration file using file.readAll(). I can open and perform the read, but can't figure out how to convert the ArrayBuffer to a string or ultimately I want to make use of the JSON in the file.
Considering the file "foo.json" in my data folder:
{
"name": "value",
"things": []
}
I'm reading it using the following code:
function readConfig() {
var file = AppFramework.file(AppFramework.userHomePath + "/ArcGIS/Runtime/Data/foo.json");
if (file.exists) {
if (file.open(File.OpenModeReadOnly)) {
var data = file.readAll();
// get the json?
file.close();
}
}
}
but I can't seem to get the text or JSON from the binary data that readAll() returns. It looks like I could use a loop and readLine() which returns a string, then check for file.atEnd, but it seems like there must be a better way.
Obviously I'm new on the QML/JS journey and would sure appreciate a push in the right direction. Thanks in advance!
Solved! Go to Solution.
Hi Mike
In the AppFramework of AppStudio there is a component called FileFolder which has methods to read/write json (and text) files which you could probably use here.
e.g. something like:
const folder = AppFramework.fileFolder(AppFramework.userHomePath + "/ArcGIS/Runtime/Data");
const jsonData = folder.readJsonFile("foo.json")
console.log(JSON.stringify(jsonData))
This code snippet works fine, but its seems silly/inefficient to have to loop through a file like this:
let data = "";
let file = AppFramework.file(filePath);
if (file.exists) {
if (file.open(File.OpenModeReadOnly)) {
do {
data += file.readLine();
} while (!file.atEnd)
file.close();
try {
let json = JSON.parse(data)
return json;
} catch(err) {
console.log("Failed to parse JSON, error returned '" + err.messsage + "'");
}
}
}
return null;
Hi Mike
In the AppFramework of AppStudio there is a component called FileFolder which has methods to read/write json (and text) files which you could probably use here.
e.g. something like:
const folder = AppFramework.fileFolder(AppFramework.userHomePath + "/ArcGIS/Runtime/Data");
const jsonData = folder.readJsonFile("foo.json")
console.log(JSON.stringify(jsonData))
Thank you! Much simpler than my approach.