使用节点动态填充对象的JSON数组

时间:2014-07-30 22:57:22

标签: javascript arrays json node.js dynamic

我知道JSON,这是我第一次使用它。

我创建了一个脚本,使用节点从广播电台网站播放音乐(艺术家和歌曲标题)。目前我通过将它们附加到文件的末尾将它们放入JSON文件中。

我想在每次找到新歌时将它们填充到数组中。我该怎么做呢?

这是我目前的代码

    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!');
                });
            }
        })
    });

目前我的JSON输出如下:

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

我想填写一系列这样的歌曲:

    {
         songs : [

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

我知道我需要使用一些东西:

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

但我不知道如何融入我的代码,任何帮助都会很可爱,谢谢你们

1 个答案:

答案 0 :(得分:1)

好的,如果我正确理解你的问题,你想加载JSON数据;然后将一首歌添加到阵列中;然后将其转换回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

这是你要找的吗?