简体   繁体   中英

How to remove redundant quotation marks in dynamically created json object with javascript?

Following problem: I want to create an Audio player with a playlist like on this site: http://www.davidorlowsky.com/player/demos/lark.htm

If you click the right mouse button and view the source code you'll see that the playlist has the following form:

[
        {
            title:"Gypsy Hora",
            artist:"Trad.",
            mp3:"http:///www.klezmorim-online.de/lark/gypsyhora.mp3"
        },
        {
            title:"Sammy's Freilach",
            artist:"Trad.",
            mp3:"http:///www.klezmorim-online.de/lark/sammysfreilach.mp3"
        },
        ...
]

What I'm trying to do is: creating this kind of playlist dynamically via parsing through a directory. This is how I try to do it:

$(document).ready(function () {                
    var sound_files = Array();
    $.ajax({
        url: "my_directory/",
        success: function (data) {
            $(data).find("td > a").each(function () {
                var file = $(this).attr("href");
                if (file.substr((file.lastIndexOf('.') + 1)) == "mp3") {
                    var mp3 = file;
                    var title= mp3.substr(0, mp3.lastIndexOf('.'));
                    //sound_files.push("{title: \""+title+"\", mp3: \"my_directory/" + mp3 + "\"}");
                    sound_files.push("{mp3: \"my_directory/" + mp3 + "\"}");
                }
            });
        }
    }).done(function () {
        console.log(sound_files);
        new jPlayerPlaylist({
            jPlayer: "#jquery_jplayer_1",
            cssSelectorAncestor: "#jp_container_1"
        }, sound_files, {
            swfPath: "jplayer",
            supplied: "oga,mp3"
        });
    });
});

It doesn't work that way and I think it's because there are redundant quotation marks in the json object. The resulting object looks like this:

["{mp3: "my_directory/my_file.mp3"}", ...]

but should look like:

[{mp3: "my_directory/my_file.mp3"}, ...]

How could I do this?

Do not push the object as string, rather do it as an object. Change this part where you are sending it:

sound_files.push("{mp3: \"my_directory/" + mp3 + "\"}");

As an object:

sound_files.push({mp3: "my_directory/" + mp3});

尝试sound_files.push({mp3: "my_directory/" + mp3});

You are currently creating strings that contain the JavaScript source code needed to construct an object.

Just create objects instead.

sound_files.push({mp3: "my_directory/" + mp3});

要获得双引号,请添加此+'“' ,一切都会起作用。但是对象方法比创建字符串要清晰得多。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM