As far as I know it is perfectly valid for JSON data to contain a top-level array, for example:
'["cat","dog"]'
The JSON standards seem to allow this and if you pass that to JSON.parse you get an array.
However, the readJsonFile and writeJsonFile methods of File Folder do not seem to allow this. If you use writeJsonFile to serialize an array to a JSON file, you get a file with just "{}" and no data. When using readJsonFIle to read from a JSON file with a top level array, you do not get the data.
Here is a short POC to reproduce the issue:
import QtQuick 2.13
import QtQuick.Controls 2.13
import ArcGIS.AppFramework 1.0
App {
id: app
width: 400
height: 640
FileFolder {
id: folder
path: "./data"
}
Text {
anchors.fill: parent
text: "{My App}"
font.pointSize: 24
color: "black"
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
}
Component.onCompleted: {
var data1 = ['cat', 'dog'];
var data2 = {animals: ['cat', 'dog']}
var okMake = folder.makeFolder();
var okWrite = folder.writeJsonFile("data1.json", data1); // This data will not be written to the JSON file
var okWrite2 = folder.writeJsonFile("data2.json", data2)
}
}
Solved! Go to Solution.
You are correct that arrays can be used in JSON at the top level. This would be considered a JSONArray. However, the FileFolder functions writeJsonFile or readJson handle JSONObjects which expect {} at top level. You can use your code snippet above and change line 33 to this and it will work.
var okWrite = folder.writeJsonFile("data1.json", {data1});
Best,
Trevor
You are correct that arrays can be used in JSON at the top level. This would be considered a JSONArray. However, the FileFolder functions writeJsonFile or readJson handle JSONObjects which expect {} at top level. You can use your code snippet above and change line 33 to this and it will work.
var okWrite = folder.writeJsonFile("data1.json", {data1});
Best,
Trevor
Thanks for the response, I guess I never considered a JSONArray to be a distinct format from a JSONObject. In javascript or python the JSON encoder functions will take either arrays or objects when writing JSON. Maybe that is different in more strictly typed languages though.
It's easy to wrap an array within an object when passing to writeJsonFile but it seems somewhat redundant to have to add that extra key when all your really care about is the array. Another option is to just use writeTextFile and readTextFile along with JSON.stringify and JSON.parse