How to transform an Array for the savefunction?

Hello again,

Could someone explain how to transform an array full of different objects, that it can be saved to a .txt or .json-file? To be more specific: I got an array that looks like the following

[
  {
    "x": 517,
    "y": 206,
    "r": 20,
    "name": "Plant a Name",
    "countScaleRounds": 13,
    "maxScaleRounds": 100,
    "scaleFactor": 0.12
  },
  {
    "x": 387,
    "y": 261,
    "r": 20,
    "name": "Plant a Name",
    "countScaleRounds": 100,
    "maxScaleRounds": 100,
    "scaleFactor": 0.99
  },
  {
    "x": 256,
    "y": 360,
    "r": 20,
    "name": "Plant a Name",
    "countScaleRounds": 85,
    "maxScaleRounds": 100,
    "scaleFactor": 0.84
  },
  {
    "x": 226,
    "y": 433,
    "r": 20,
    "name": "Plant a Name",
    "countScaleRounds": 73,
    "maxScaleRounds": 100,
    "scaleFactor": 0.72
  }
]

and when save() is used, the result is a textfile with [object Object],[object Object],... but not the data from the array. Now I'm hopping that some of the advanced programmasters can explain me what I'm missing out. Thx in advance.

the saving part in my script look like this:

  function keyTyped() {
     if (key === 's' || key === 'S') {
     saveStrings(plants,"plants.txt");
     println(plants.txt);
     }
}

Answers

  • Answer ✓

    The problem is that your array contains Objects (defined using JSON) and not plain text. The solution is simple enough these days:

    function keyTyped() {
         if (key === 's' || key === 'S') {
    
            var plantsAsStrings = plants.map(JSON.stringify);
    
            saveStrings(plantsAsStrings, "plants.txt");
         }
    }
    

    map is a super-handy array method that saves you manually iterating over your array to create an altered copy. The alteration is performed by the function you pass to map; in this case JSON.stringify; which does exactly what it says on the tin :)

  • edited February 2017 Answer ✓

    https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text

    http://p5js.org/reference/#/p5/saveJSON

    http://p5ide.HerokuApp.com/editor#?sketch=5767154be4a5cc03001829f5

    <script async src=http://CDN.JSDelivr.net/p5.js/latest/mainfile></script>
    
    <script>
    
    /**
     * saveJSON() Sample (v1.1)
     * GoToLoop (2016-Jun-19)
     * 
     * https://forum.Processing.org/two/discussion/17220/
     * how-to-transform-an-array-for-the-savefunction#Item_2
     *
     * http://p5ide.HerokuApp.com/editor#?sketch=5767154be4a5cc03001829f5
    */
    
    "use strict";
    
    const PLANTS_JSON = [
      {
        "x": 517,
        "y": 206,
        "r": 20,
        "name": "Henbane",
        "countScaleRounds": 13,
        "maxScaleRounds": 100,
        "scaleFactor": 0.12
      },
      {
        "x": 387,
        "y": 261,
        "r": 20,
        "name": "Cinquefoil",
        "countScaleRounds": 100,
        "maxScaleRounds": 100,
        "scaleFactor": 0.99
      },
      {
        "x": 256,
        "y": 360,
        "r": 20,
        "name": "Hemlock",
        "countScaleRounds": 85,
        "maxScaleRounds": 100,
        "scaleFactor": 0.84
      },
      {
        "x": 226,
        "y": 433,
        "r": 20,
        "name": "Aconite",
        "countScaleRounds": 73,
        "maxScaleRounds": 100,
        "scaleFactor": 0.72
      }
    ];
    
    const JSON_FILENAME = 'venomous_plants.json';
    
    function preload() { loadJSON(JSON_FILENAME, console.table.bind(console)); }
    
    function setup() {
      noCanvas();
      saveJSON(PLANTS_JSON, JSON_FILENAME, false);
    }
    
    </script>
    
  • :))

    That'll teach me for assuming someone had checked the docs properly...

  • edited June 2016

    Thank you @blindfish and @GoToLoop. Will try your answers soon.

    But I have to tell you one question more:

    1) If the Array gets stringifiyed, is it still possible to load the JSON-File and use it as before?

    2) The script is creating a Json-file out of a constant json-file, what if my array is not so constant? objects might get added from time to time...is it still possible to use the same scriptlogic?

    Thank's again in advance

    p.s. previous post has been reformated, thanks for the silent hint.

  • edited June 2016

    2) The script is creating a JSON-file out of a constant json-file, what if my array is not so constant?

    • Keyword const affects the variable itself only:
      https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
    • It merely means that any variable declared w/ const can't be reassigned later w/ = or its other composite forms.
    • That is, any object that some variable points to can still be mutated freely, regardless whether the variable is const or not. O:-)
    • However, if the object is intended to be mutable, by convention, its variable name should be lowerCamelCase instead of ALL_CAPS: PLANTS_JSON -> plantsJson. L-)
  • saveJson with stringify worked as intendet. I read about the function .parse which should allow the programm to transform the data back to original. p5js-editor says "OK" but reality says [-( nope.

    as I'm a beginner, I would appreciate a hint how .parse get used correctly? I tried the following code:

    function keyTyped() {
      var test;
      var test2;
      if (key === 'l' || key === 'L') { //At the moment it is not really working
        test = loadJSON("plants.json"); 
        test2 = JSON.parse(test);
        console.log(test);
        console.log(test2);
      }
    }
    
  • Answer ✓

    In my example, there was no need to use stringify() at all:
    https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    Actually, saveJSON() demands an array or object, not a string:
    http://p5js.org/reference/#/p5/saveJSON

    And in the same vein, loadJSON() returns either an array or an object:
    http://p5js.org/reference/#/p5/loadJSON

    Method parse() is the opposite of stringify(). Converts a string back to its corresponding array or object:
    https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

  • Thanks GoToLoop, tried your code as well on heruku, but could't get the loadfunction to work. In the new typed testsketch it also doesn't like to load the saved data...hmmm... p5ide.herokuapp.com/editor#?sketch=57699e046965890300a7ac20

    const plantJson = [];
    
    function setup() {
      createCanvas(400, 400);
    
    }
    
    function draw() {
      background(220);
      if (mouseIsPressed === true) {
        plantJson.push ("x",mouseX,99.0012);
      }
      println(plantJson);
    }
    
    function keyTyped (){
      if (key === 's') {
        saveJSON (plantJson, "plants.json", false);
      }
      if (key === 'l') {
        loadJSON ("file:///E:/Program%20Files%20E/P5/TestJSON/plants.json",draw());
        println(plantJson);
      }
    }
    

    I am certain that there is something inapprehensible in my logic.

  • Sorry to repost, but the script is now working somehow. That is the code: p5ide.herokuapp.com/view/57699e046965890300a7ac20

    const plantJson = [];
    var plantJson2=[];
    
    function setup() {
      createCanvas(400, 400);
    
    }
    
    function draw() {
      background(220);
      if (mouseIsPressed === true) {
        plantJson.push ("x",mouseX,99.0012);
          println(plantJson);
      }
    
    }
    
    function keyTyped (){
      if (key === 's') {
        saveJSON (plantJson, "plants.json", false);
      }
      if (key === 'l') {
        plantJson2=loadJSON ("plants(1).json",console.log(plantJson2));
        println(plantJson2);
      }
    }
    
Sign In or Register to comment.