-1

I have unformatted data in my data.json file. I have formatted it using javascript. Now I have to dump formatted data into newData.json file. But I am not able to find correct code. Please suggest how can I dump json data into newData.json file.

 $.getJSON( "movie.json", function( data ) {
var result = {
    Win: {},
    Nominated: {}
};

data.forEach( obj => {
    var stats = result[obj.WinType][obj.Nominee] = result[obj.WinType][obj.Nominee] || {
        count: 0,
        rating: 0,
        0: 0,
        name: obj.Nominee
    };
    stats.rating += obj.RATING;
    stats.count++;
    stats[0] += obj.WinProbability * 100;
});

Object.keys(result).forEach( grp =>
    result[grp] = Object.keys(result[grp]).map( name => {
        var stats = result[grp][name];
        stats[0] /= 100;
        stats[1] = Math.round(stats.rating * 100 / stats.count) / 100;
        delete stats.count;
        delete stats.rating;
        return stats;
    })
);
console.log(result);
});
sandip kakade
  • 1,346
  • 5
  • 23
  • 49

1 Answers1

1

Lets say you have your new data into the results variable.

You could write the results to a new file and download the same. But you can't write the data to a file on your server. If you need to write data to server then you will have to create an api which gets the data on the server and then it writes the same into a new file which will then be available for you to access from browser just like the file 'movie.json'

Approach 1:

var result = {'your new data'}
var url = 'data:text/json;charset=utf8,' + encodeURIComponent(result);
window.open(url, '_blank');

This will allow you to download the file with the new data.

Approach 2:

You have an API written on server that expects JSON data which will write to a file in the public directory so its available on client.

$.ajax({
  type: "POST",
  url: '/api/new_data',
  data: result,
  success: function(){console.log('success')}
});

This is an example of how it can be done. You will have to write your own api to accept the POST request and write to a file.

Hope it helps.

Pramod Solanky
  • 1,690
  • 15
  • 17