zlwaterfield
zlwaterfield

Reputation: 841

Dynamically fill JSON array of objects using node

I am knew to JSON, this is the first time i have worked with it.

I have created a script using node to pull music(Artists and Song Titles) from a radio stations website as the radio station plays them. Currently i am putting them into a JSON file by appending them to the end of the file.

I would like to fill them into an array each time a new song is found instead. How do i go about doing this?

Here is my current code

    var fs = require('fs');
    var request = require('request');
    var cheerio = require('cheerio');
    var schedule = require('node-schedule');

    var rule = new schedule.RecurrenceRule();
    //Timer to run every 3 minutes (average song time)
    rule.minute = new schedule.Range(0, 59, 3);

    var j = schedule.scheduleJob(rule, function(){
        console.log('LOADING.......................');

        //URL for site you want to get the Songs from
        url = '#';

        request(url, function(error, response, html){
            if(!error){
                var $ = cheerio.load(html);

                var artist, stitle;

                var songs = {artist : "", stitle : ""};

                //ID for artist
                $('#').each(function(){
                    var data = $(this);
                    artist = data.text();

                    songs.artist = artist;
                })

                //ID for song title
                $('#').each(function(){
                    var data = $(this);
                    stitle = data.text();

                    songs.stitle = stitle;
                })
            }

            //Reading current list of songs
            var content;
            content = fs.readFileSync('output.json', "utf8"); 

            //Searching current list for song it wants to add
            var text = content;
            var search = text.search(stitle);

            //Only adding song if it cant find new song in list
            if(search >= 0) {
                console.log('Song already exists');
            } else  {
                fs.appendFile('output.json', JSON.stringify(songs, null, 4) + ",\n", function (err) {
                    console.log('Song successfully added!');
                });
            }
        })
    });

Currently my JSON output looks like:

    {
        "artist": "FOO FIGHTERS",
        "stitle": "BEST OF YOU"
    },
    {
        "artist": "GAY NINETIES",
        "stitle": "LETTERMAN"
    },
    {
        "artist": "VANCE JOY",
        "stitle": "RIPTIDE"
    },
    {
        "artist": "NIRVANA",
        "stitle": "IN BLOOM"
    }

I would like to fill an array of songs like this:

    {
         songs : [

            {
                "artist": "FOO FIGHTERS",
                "stitle": "BEST OF YOU"
            },
            {
                "artist": "GAY NINETIES",
                "stitle": "LETTERMAN"
            },
            {
                "artist": "VANCE JOY",
                "stitle": "RIPTIDE"
            },
            {
                "artist": "NIRVANA",
                "stitle": "IN BLOOM"
            }
        ]
    }

I know that i need to use something alongs the lines:

var songs = [];
for (var song in songs) {
    songs.push({artist : "", stitle : ""});
}

But i don't know how to incorporate into my code, any help would be lovely, thanks guys

Upvotes: 0

Views: 5116

Answers (1)

Oscar
Oscar

Reputation: 678

Okay, so if I understand your question correctly, you would like to load the JSON data; then append a song into the array; and then convert it back into JSON?

// load new song data first:
var newSong = {
    artist: "FOO BAR FIGHTERS",
    stitle: "IF THEN ELSE"
}

// then load data:
var jsonString = "[{:[,],:}]" // load JSON file here!
var data = JSON.parse(jsonString) // turn JSON string into an actual object

/*
at this point, you have access to data.song,
which is the array of all songs in the list.
*/

// now check if it's already in the list:
var alreadyInList = false
for(var i = 0; i < data.song.length; i ++)
{
    if(data.song[i].stitle === newSong.stitle) alreadyInList = true
}

// if not, push it:
if(!alreadyInList) data.song.push(newSong)

// then stringify the object again for storage:
var backToString = JSON.stringify(data)
console.log(data) // output back to file

Is this what you're looking for?

Upvotes: 1

Related Questions