A
A
Alexander Lebedev2016-07-15 17:21:36
JavaScript
Alexander Lebedev, 2016-07-15 17:21:36

How to upload data from JSON to local html?

Good evening.
There is a playback.json json file with the following structure:

{
    "playing": true,
    "song": {
        "title": "Can't Get You out of My Head",
        "artist": "Jack Lukeman",
        "album": "Sunday Independent",
        "albumArt": "https://lh3.googleusercontent.com/q8vGPE-zyi0Kr6XzhHijz3-Nu0bPflB2wfSSJIfyIIxAYr8rouf8PWnni_LFMrp3tmHu1sCMVA"
    },
    "rating": {
        "liked": false,
        "disliked": false
    },
    "time": {
        "current": 101576,
        "total": 185000
    },
    "songLyrics": null,
    "shuffle": "NO_SHUFFLE",
    "repeat": "NO_REPEAT"
}

I need to upload the title / track / cover from it to an HTML file, so that later I can pull it into the broadcast from this file. Accordingly, it is necessary that the contents of the file change when the song changes. The problem is that I do not quite understand how to do this, because my version after a couple of hours of torment:
$(function(){
    $.getJSON('playback.json', function(data) {
            for(var i=0;i<data.song.length;i++){
                $('#song').append('<tr><td>' + data.song[i].title);
            }
    });
});

doesn't work at all. I would be grateful for any help or ready to pay as a small order :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MetaDone, 2016-07-15
@MetaDone

Maybe your original json is being given as a string in html and not as a json object.
Try this:
$.getJSON('playback.json', function(data) {
data = JSON.parse(data);
...
if it becomes normal, then the problem is this

D
Denis, 2016-07-15
@Deonisius

Working with objects is somewhat different from working with arrays ( array-like objects )

$(function() {
    $.getJSON('playback.json', function(data) {
        for (var key in data.song) {
            if (data.song.hasOwnProperty(key)) {
                $('#song').append('<tr><td>' + data.song[key]);
            }
        }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question