Click here to Skip to main content
13,048,584 members (79,635 online)
Rate this:
Please Sign up or sign in to vote.
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:

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 21:50pm
Updated 18-Mar-13 22:20pm

1 solution

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

Solution 1


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.

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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 19 Mar 2013
Copyright © CodeProject, 1999-2017
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