AppFramework.file.readAll()

740
3
Jump to solution
06-11-2020 07:22 AM
MikeQuetel1
Occasional Contributor

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!

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
by Anonymous User
Not applicable

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.

FileFolder QML Type | ArcGIS 

e.g. something like:

const folder = AppFramework.fileFolder(AppFramework.userHomePath + "/ArcGIS/Runtime/Data");
const jsonData = folder.readJsonFile("foo.json")
console.log(JSON.stringify(jsonData))

View solution in original post

3 Replies
MikeQuetel1
Occasional Contributor

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;‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
by Anonymous User
Not applicable

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.

FileFolder QML Type | ArcGIS 

e.g. something like:

const folder = AppFramework.fileFolder(AppFramework.userHomePath + "/ArcGIS/Runtime/Data");
const jsonData = folder.readJsonFile("foo.json")
console.log(JSON.stringify(jsonData))
MikeQuetel1
Occasional Contributor

Thank you! Much simpler than my approach.

0 Kudos