Saturday, October 18, 2025
HomeLanguagesJavascriptp5.js saveJSON() Function

p5.js saveJSON() Function

The saveJSON() function is used to write an object or array of objects as a JSON object to the .json file. The saving of the file will vary depending on the web browser.

Syntax:

saveJSON( json, filename, optimize )

Parameters: This function accept three parameters as mentioned above and described below:

  • json: It is an object or array of objects that will form the contents of the JSON object to be created.
  • filename: It specifies the string that is used as the filename of the saved file.
  • optimize: It is a boolean value which specifies if the JSON object would be removed of line breaks and spaces before it is written. It is an optional parameter.

The examples below illustrate the saveJSON() function in p5.js:

Example 1:




function setup() {
  createCanvas(600, 300);
  textSize(22);
  text("Click on the button below to "
      + "save the JSON Object", 20, 20);
  
  bookObj = {};
  bookObj.name = "Let US C";
  bookObj.author = "Yashavant Kanetkar";
  bookObj.price = "120";
  
  // Create a button for saving the JSON Object
  saveBtn = createButton("Save JSON object to file");
  saveBtn.position(30, 50)
  saveBtn.mousePressed(saveFile);
}
  
function saveFile() {
  
  // Save the JSON object to file
  saveJSON(bookObj, 'books.json', true);
}


Output:
save-json-obj

Example 2:




function setup() {
  createCanvas(600, 300);
  textSize(22);
  text("Click on the button below to "
      + "save the JSON Array", 20, 20);
  
  bookArray = [];
  
  for (let i = 1; i <= 3; i++) {
    bookObj = {};
    bookObj.name = "Book " + i;
    bookObj.author = "Author " + i;
  
    bookArray.push(bookObj);
  }
  
  // Create a button for saving JSON Object
  saveBtn = createButton("Save JSON Array to file");
  saveBtn.position(30, 50)
  saveBtn.mousePressed(saveFile);
}
  
function saveFile() {
  
  // Save the JSON object to file
  saveJSON(bookArray, 'books-list.json');
}


Output:
save-json-array

Online editor: https://editor.p5js.org/

Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

Reference: https://p5js.org/reference/#/p5/saveJSON

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS