Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript JSONiq
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:
 
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 18-Mar-13 22:50pm
Edited 18-Mar-13 23:20pm
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hello,
 
This is how you will do this.
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,
  Permalink  
Comments
Member 8155312 at 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)

  Print Answers RSS
0 OriginalGriff 587
1 Sergey Alexandrovich Kryukov 479
2 Maciej Los 305
3 Mathew Soji 195
4 Richard MacCutchan 145
0 OriginalGriff 7,356
1 Sergey Alexandrovich Kryukov 6,712
2 DamithSL 5,461
3 Manas Bhardwaj 4,916
4 Maciej Los 4,475


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 19 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100