Adding an existing 2 dimensional array to a JSONObject

Hi everyone,

I am fairly new to Java and Processing, …coming from Javascript many things still look like black magic to me :slight_smile:
I am trying to format some data to JSON to send via websockets to an esp32 board. In JS its very straighforward since well, JSON is Javascript…

Here is a simplified version of my code:

// Variables
JSONObject json;
String jsonString;
String [][] myHexFrame;
int fps;

// These are inside a function
json = new JSONObject();                  // Create a new JSON object. OK.
json.setInt("fps", fps);                  // Add a simple integer. Works no problem.
// json.setJSONArray("colors", myHexFrame);  <-- The 2nd parameter should be... a JSONArray?
// How can I convert a "non JSON" array to a JSON one?
// Should I loop trough all values and push them one by one?
// Is there some kind of map() function to do that?
jsonString = json.toString(); // Stringify the whole thing. OK
ws.sendMessage(jsonString);   // ..then send it. OK

The myHexFrame array was filled earlier in the code with hex values.

String [][] myHexFrame = [
  ['0x2C699C', '0x2B6C9D', ...], // 64 columns
  ['0x2C699C', '0x2B6C9D', ...],
  ...]; // And 64 rows

Ultimately I’d like to have a JSON object looking like this:

json = {
  "fps": 60,
  "myHexFrame": [
    ['0x2C699C', '0x2B6C9D', ...],
    ['0x2C699C', '0x2B6C9D', ...],
  "aString": "Here comes a string",

Thanks a lot!

Maybe this JSONArray / Reference /

Also, a 2d array is probably an array of arrays

Hi @remka,

Look here…

— mnse

Hello @remka,



String[][] hexFrame = { 
                      {"0xA00000", "0xB00000", "0xC00000", "0xD00000"},
                      {"0x000000", "0x100000", "0x200000", "0x300000"}

JSONObject jsonObject = new JSONObject();

jsonObject.put("fps",  60);
jsonObject.put("myHexFrame", hexFrame);


String s = jsonObject.toString();
s = s.replaceAll("\\s+", "");

saveJSONObject(jsonObject, "data/new.json");


"myHexFrame": [
  "fps": 60




Thanks @glv, put() was all I needed. Not sure why this is not listed on this page.
I guess I was a bit confused with the java syntax for arrays too ^^

1 Like

You are welcome!

The Javadoc’s have additional information:

You can also enable Code completion with CTRL-space and will see it:


1 Like