Click here to Skip to main content
15,886,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]


I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:

JavaScript
function createData() {
    //original, single json object
    var dataToSave = {"result": '"' + toLength.innerText +'"', //taking value from DOM
            "count":  counter       //counter = counter + 1;
    };

     //save into an array:
     var dataArray = { [] };    //No idea how to go ahead.. 


     var savedData = JSON.stringify(dataToSave);    
     writeToFile(filename, savedData);  //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.

}
function readData(data) {
    var dataToRead = JSON.parse(data);

     var message = "Your Saved Conversions : ";

     message += dataToRead.result;

     document.getElementById("savedOutput1").innerText = message;
}
Posted
Updated 18-Mar-13 22:20pm
v2

1 solution

Hello,

This is how you will do this.
JavaScript
function createData() {
    //original, single json object
    var dataToSave = {"result": '"' + toLength.innerText +'"', "count":  counter};
 
     //save into an array:
     var dataArray = new Array();    //No idea how to go ahead.. 
     dataArray[0] = dataToSave;
     // Add more if required
     // dataArray[1] = {"result": '"' + toLength2.innerText +'"', "count": counter2};

     var savedData = JSON.stringify(dataArray);    
     writeToFile(filename, savedData);
}

Note: Please note that in a browser this is not going to work, as for security reasons browser is not going to allow javascript to acess the local file system depending upon the zone in which the site is running.

Regards,
 
Share this answer
 
Comments
Member 8155312 19-Mar-13 4:50am    
I'm trying to develop a Windows 8 app, so file I/O is not a problem. Your solution works to save data in a formatted version. Thanks..,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900