I have tried evey which way to get this function to work…
Anybody got a working example ?
Here is my Json array: [{“id”: “1”}]
I couldn’t make it any simpler. Or am I barking up the wrong tree ?
Its reference states: “(All values in the array must be of the String type.)”
However your JSONArray contains an JSONObject and not a string, which isn’t valid:
[{"id": "1"}]
Should be instead something like this:
[ "id", "1" ]
JSONArray loopData;
loopData = loadJSONArray(“data.json”);
println(loopData);
String strngArray = loopData.toStringArray();
loads a JSON Array from file - containing [{“id”: “1”}]
That is the minimum that the loadJSONArray will accept.
This why I was asking for a working example.
Thanks for the response - [ “id”,“id2”] does load correctly and IS converted to a String
But that is Soooooo limited.
I will have to do a manual conversion as my JSONArray contains Arrays, Objects etc.
Hello @dneilan,
This is an interesting topic and I am interested in your manual conversion.
A simple example will suffice.
This was a very quick effort for me and the data was straightforward from one of the Processing examples:
// Reference:
// https://www.freecodecamp.org/news/jsonobject-tostring-how-to-convert-json-to-a-string-in-java/
String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" };
String[] names = { "Goat", "Leopard", "Zebra" };
JSONArray values;
String [] JSONtoArr;
void setup()
{
values = new JSONArray();
for (int i = 0; i < species.length; i++)
{
JSONObject animal = new JSONObject();
animal.setInt("id", i);
animal.setString("species", species[i]);
animal.setString("name", names[i]);
values.setJSONObject(i, animal);
}
String s = values.toString();
println(s);
println();
JSONtoArr = split(s, '\n');
printArray(JSONtoArr );
println();
for(int i=0; i< JSONtoArr.length; i++)
{
JSONtoArr[i] = JSONtoArr[i].trim();
JSONtoArr[i] = JSONtoArr[i].replaceAll("\"", "");
}
printArray(JSONtoArr);
println();
saveStrings("test.txt", JSONtoArr);
}
I always enjoy the challenge of custom parsing data to access elements and wield them with code.
Have fun!
:)
import java.util.Arrays;
String[] words = {"go", "to ", "school"};
println(Arrays.toString(words)); //print [go, to , school]
printArray(words);
//print
// [0] "go"
//[1] "to "
//[2] "school"
Gee thanks. Not helpful