Ketika sebaris kode tak berhenti menatap dan tampak naksir kepada Anda.

Parser JSON untuk Blogger · Posting dan Halaman Statis

Berikut adalah generalisasi fungsi untuk mengubah data JSON posting dan halaman statis Blogger menjadi markup HTML sesuai dengan keinginan. Di sini Saya membagi fungsinya menjadi dua macam yaitu generatePostsData untuk menangani posting dan halaman dalam bentuk daftar dan generatePostData untuk menangani posting dan halaman dalam bentuk tunggal:

Bentuk Daftar

function generatePostsData(json) {

    // Poor configuration settings, develop them yourself!
    var config = {
        containerID: 'result-container', // Container ID to show the generated data
        avatarSize: 50, // Default avatar size
        noThumbnail: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABIAQMAAABvIyEEAAAABGdBTUEAALGPC/xhBQAAAAZQTFRFOjo6JycnNkxyjQAAADZJREFUKM9j+A8DDFRnNTCAACP9WewPGNgfkMmiwN7GH0CGfCPdWZT5V/7/DwZyWeSHFa1SHQDDGF2E0US40gAAAABJRU5ErkJggg==',
        text: {
            anon: 'Anonymous',
            untagged: 'Untagged',
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
        }
    };

    var html = "",
        item = "",
        w = window,
        d = document,
        feed = json.feed,
        container = d.getElementById(config.containerID),
        postTotal = +feed.openSearch$totalResults.$t, // The post/page feeds' total (all)
        postStartIndex = +feed.openSearch$startIndex.$t, // The post/page feeds' start index
        postPerPage = +feed.openSearch$itemsPerPage.$t, // The post/page feeds' max results per page or per feed request
        blogID = /\:blog-?(\d+)(\.|$)/.exec(feed.id.$t) ? /\:blog-?(\d+)(\.|$)/.exec(feed.id.$t)[1] : false, // The blog ID
        blogTitle = feed.title.$t, // The post/page feeds' title
        blogTags = false, // The available post/page tags (all)
        blogSubTitle = feed.subtitle.$t, // The post/page feeds' subtitle
        blogAuthorName = feed.author[0].name ? feed.author[0].name.$t : config.text.anon, // The blog/post author name
        blogAuthorAvatar = feed.author[0].gd$image.src.replace(/\/s\d+(\-c)?\//, '/s' + config.avatarSize + '-c/'), // The blog/post author profile avatar URL
        blogGeneratorName = feed.generator.$t, // The blog generator name (Blogger)
        blogGeneratorURL = feed.generator.uri; // The blog generator URL (http://www.blogger.com)

    // Remove the leading `http://` or `https://` in blog/post author profile avatar URL
    // blogAuthorAvatar = blogAuthorAvatar.replace(/^https?\:/, "");

    // No container found
    if (!container) {
        alert('Container not found.');
        return;
    }

    // Getting the blog tags
    if (feed.category && feed.category.length) {
        blogTags = [];
        for (var h = 0, hen = feed.category.length; h < hen; ++h) {
            blogTags.push(feed.category[h].term);
        }
        // Sort the blog tags alphabetically
        blogTags = blogTags.sort();
    }

    // No posts/pages yet
    if (!feed.entry || feed.entry.length === 0) {
        container.innerHTML = '<p>No posts/pages yet.</p>';
        return;
    }

    // Building the markup ...
    html += '<h1>' + blogTitle + '</h1>';
    html += '<h2>' + blogSubTitle + '</h2>';
    html += '<p><b>Blog ID:</b> ' + blogID + '</p>';
    html += '<p><b>Blog Tags:</b> ' + (blogTags !== false ? blogTags.join(', ') : config.text.untagged) + '</p>';
    html += '<p><b>Blog Author Name:</b> ' + blogAuthorName + '</p>';
    html += '<p><b>Blog Author Avatar URL:</b> ' + blogAuthorAvatar + '</p>';
    html += '<p><b>Total Posts:</b> ' + postTotal + '</p>';
    html += '<p><b>Posts Per Page:</b> ' + postPerPage + '</p>';
    html += '<p><b>Posts Start Index:</b> ' + postStartIndex + '</p>';
    html += '<hr>';
    html += '<ol>';

    var posts = feed.entry;

    for (var i = 0, ien = posts.length; i < ien; ++i) {
    
        var post = posts[i], // A single post/page object
            postID = post.id.$t, // The post/page ID
            postPublish = post.published.$t, // The post/page publishing time in ISO format
            postUpdate = post.updated.$t, // The post/page updating time in ISO format
            postDate = postPublish, // The post/page publishing time in human-readable format
            postURL = false, // The post/page URL
            postTags = false, // The post/page tags
            postCommentTotal = post.thr$total ? +post.thr$total.$t : 0, // The post/page comments total
            postCommentFeedURL = false, // The post/page comments feed URL
            postThumbnail = post.media$thumbnail ? post.media$thumbnail.url : config.noThumbnail, // The post/page thumbnail
            postAuthorName = post.author[0].name ? post.author[0].name.$t : config.text.anon, // The post/page author name
            postAuthorURL = post.author[0].uri ? post.author[0].uri.$t : false, // The post/page author profile URL
            postAuthorAvatar = post.author[0].gd$image.src.replace(/\/s\d+(\-c)?\//, '/s' + config.avatarSize + '-c/'), // The post/page author profile avatar URL
            postTitle = post.title.$t, // The post/page title
            postContent = post.content ? post.content.$t : post.summary.$t.replace(/<br *\/?>|[\s]+/gi, ' ').replace(/<.*?>|[<>]/g, ""), // The post/page content
            postEditURL = false; // The post/page edit URL

        // Generate human-readable post/page date format
        var date = postDate.split('T')[0].split('-');
        postDate = date[2] + ' ' + config.text.monthNames[(+date[1]) - 1] + ' ' + date[0];

        // Remove the leading `http://` or `https://` in post/page thumbnail URL
        // postThumbnail = postThumbnail.replace(/^https?\:/, "");

        // Remove the leading `http://` or `https://` in post/page author profile avatar URL
        // postAuthorAvatar = postAuthorAvatar.replace(/^https?\:/, "");

        for (var j = 0, jen = post.link.length; j < jen; ++j) {
            item = post.link[j];
            if (item.rel == 'self') {
                // Getting the original post/page ID
                postID = item.href.split('/').pop();
                // Getting the post/page edit URL
                postEditURL = item.href.replace(/\/feeds\/(\d+)\/(post|page)s?\/(default|summary)\/(\d+)/, '/$2-edit.g?blogID=$1&$2ID=$4');
            }
            // Getting the post/page URL
            if (item.rel == 'alternate') {
                postURL = item.href;
            }
            // Getting the post/page comment feed URL
            if (item.rel == 'replies' && item.type == 'application/atom+xml') {
                postCommentFeedURL = item.href;
            }
        }

        // Trying to get the external image URL from post/page content
        if (post.content && postThumbnail == config.noThumbnail) {
            var image = /<img +(.*?)src=(['"])([^'"]+?)(['"])(.*?) *\/?>/i.exec(post.content.$t);
            postThumbnail = image && image[3] ? image[3] : config.noThumbnail;
        }

        // Getting the post/page tags
        if (post.category && post.category.length) {
            postTags = [];
            for (var k = 0, ken = post.category.length; k < ken; ++k) {
                postTags.push(post.category[k].term);
            }
            // Sort the post/page tags alphabetically
            postTags = postTags.sort();
        }

        // Building the markup ...
        html += '<li>';
        html += '<p><b>ID:</b> ' + postID + '</p>';
        html += '<p><b>Publish:</b> ' + postPublish + '</p>';
        html += '<p><b>Update:</b> ' + postUpdate + '</p>';
        html += '<p><b>Date:</b> ' + postDate + '</p>';
        html += '<p><b>URL:</b> ' + postURL + '</p>';
        html += '<p><b>Tags:</b> ' + (postTags !== false ? postTags.join(', ') : config.text.untagged) + '</p>';
        html += '<p><b>Comment Total:</b> ' + postCommentTotal + '</p>';
        html += '<p><b>Comment Feed URL:</b> ' + postCommentFeedURL + '</p>';
        html += '<p><b>Thumbnail:</b> ' + postThumbnail + '</p>';
        html += '<p><b>Author:</b> ' + postAuthorName + '</p>';
        html += postAuthorURL !== false ? '<p><b>Author URL:</b> ' + postAuthorURL + '</p>' : "";
        html += '<p><b>Author Avatar URL:</b> ' + postAuthorAvatar + '</p>';
        html += '<p><b>Edit URL:</b> ' + postEditURL + '</p>';
        html += '<p><b>Title:</b> ' + postTitle + '</p>';
        html += '<p><b>Content:</b></p>';
        html += '<div>' + postContent + '</div>';
        html += '</li>';

    }

    // Building the markup ...
    html += '</ol>';

    // Show the generated data to the container ...
    container.innerHTML = html;

}

Penggunaan

Urutannya dimulai dari penulisan HTML untuk menampung data yang akan digenerasikan oleh fungsi di atas, dilanjutkan dengan memasukkan fungsi di atas ke dalam tag <script>, lalu memanggil data JSON dengan menggunakan nilai parameter URL callback berupa generatePostsData, sesuai dengan nama fungsi di atas:

<div id="result-container">Loading&hellip;</div>
<script>
function generatePostsData(json) { … }
</script>
<script src="//nama_blog.blogspot.com/feeds/posts/default?alt=json-in-script&orderby=published&callback=generatePostsData"></script>

Bentuk Tunggal

function generatePostData(json) {

    // Poor configuration settings, develop them yourself!
    var config = {
        containerID: 'result-container', // Container ID to show the generated data
        avatarSize: 50, // Default avatar size
        noThumbnail: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABIAQMAAABvIyEEAAAABGdBTUEAALGPC/xhBQAAAAZQTFRFOjo6JycnNkxyjQAAADZJREFUKM9j+A8DDFRnNTCAACP9WewPGNgfkMmiwN7GH0CGfCPdWZT5V/7/DwZyWeSHFa1SHQDDGF2E0US40gAAAABJRU5ErkJggg==',
        text: {
            anon: 'Anonymous',
            untagged: 'Untagged',
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
        }
    };

    var html = "",
        item = "",
        w = window,
        d = document,
        container = d.getElementById(config.containerID);

    // No container found
    if (!container) {
        alert('Container not found.');
        return;
    }

    var post = json.entry, // The post/page object
        postID = post.id.$t, // The post/page ID
        postPublish = post.published.$t, // The post/page publishing time in ISO format
        postUpdate = post.updated.$t, // The post/page updating time in ISO format
        postDate = postPublish, // The post/page publishing time in human-readable format
        postURL = false, // The post/page URL
        postTags = false, // The post/page tags
        postCommentTotal = post.thr$total ? +post.thr$total.$t : 0, // The post/page comments total
        postCommentFeedURL = false, // The post/page comments feed URL
        postThumbnail = post.media$thumbnail ? post.media$thumbnail.url : config.noThumbnail, // The post/page thumbnail
        postAuthorName = post.author[0].name ? post.author[0].name.$t : config.text.anon, // The post/page author name
        postAuthorURL = post.author[0].uri ? post.author[0].uri.$t : false, // The post/page author profile URL
        postAuthorAvatar = post.author[0].gd$image.src.replace(/\/s\d+(\-c)?\//, '/s' + config.avatarSize + '-c/'), // The post/page author profile avatar URL
        postTitle = post.title.$t, // The post/page title
        postContent = post.content ? post.content.$t : post.summary.$t.replace(/<br *\/?>|[\s]+/gi, ' ').replace(/<.*?>|[<>]/g, ""), // The post/page content
        postEditURL = false; // The post/page edit URL

    // Generate human-readable post/page date format
    var date = postDate.split('T')[0].split('-');
    postDate = date[2] + ' ' + config.text.monthNames[(+date[1]) - 1] + ' ' + date[0];

    // Remove the leading `http://` or `https://` in post/page thumbnail URL
    // postThumbnail = postThumbnail.replace(/^https?\:/, "");

    // Remove the leading `http://` or `https://` in post/page author profile avatar URL
    // postAuthorAvatar = postAuthorAvatar.replace(/^https?\:/, "");

    for (var j = 0, jen = post.link.length; j < jen; ++j) {
        item = post.link[j];
        if (item.rel == 'self') {
            // Getting the original post/page ID
            postID = item.href.split('/').pop();
            // Getting the post/page edit URL
            postEditURL = item.href.replace(/\/feeds\/(\d+)\/(post|page)s?\/(default|summary)\/(\d+)/, '/$2-edit.g?blogID=$1&$2ID=$4');
        }
        // Getting the post/page URL
        if (item.rel == 'alternate') {
            postURL = item.href;
        }
        // Getting the post/page comment feed URL
        if (item.rel == 'replies' && item.type == 'application/atom+xml') {
            postCommentFeedURL = item.href;
        }
    }

    // Trying to get the external image URL from post/page content
    if (post.content && postThumbnail == config.noThumbnail) {
        var image = /<img +(.*?)src=(['"])([^'"]+?)(['"])(.*?) *\/?>/i.exec(post.content.$t);
        postThumbnail = image && image[3] ? image[3] : config.noThumbnail;
    }

    // Getting the post/page tags
    if (post.category && post.category.length) {
        postTags = [];
        for (var k = 0, ken = post.category.length; k < ken; ++k) {
            postTags.push(post.category[k].term);
        }
        // Sort the post/page tags alphabetically
        postTags = postTags.sort();
    }

    // Building the markup ...
    html += '<li>';
    html += '<p><b>ID:</b> ' + postID + '</p>';
    html += '<p><b>Publish:</b> ' + postPublish + '</p>';
    html += '<p><b>Update:</b> ' + postUpdate + '</p>';
    html += '<p><b>Date:</b> ' + postDate + '</p>';
    html += '<p><b>URL:</b> ' + postURL + '</p>';
    html += '<p><b>Tags:</b> ' + (postTags !== false ? postTags.join(', ') : config.text.untagged) + '</p>';
    html += '<p><b>Comment Total:</b> ' + postCommentTotal + '</p>';
    html += '<p><b>Comment Feed URL:</b> ' + postCommentFeedURL + '</p>';
    html += '<p><b>Thumbnail:</b> ' + postThumbnail + '</p>';
    html += '<p><b>Author:</b> ' + postAuthorName + '</p>';
    html += postAuthorURL !== false ? '<p><b>Author URL:</b> ' + postAuthorURL + '</p>' : "";
    html += '<p><b>Author Avatar URL:</b> ' + postAuthorAvatar + '</p>';
    html += '<p><b>Edit URL:</b> ' + postEditURL + '</p>';
    html += '<p><b>Title:</b> ' + postTitle + '</p>';
    html += '<p><b>Content:</b></p>';
    html += '<div>' + postContent + '</div>';
    html += '</li>';

    // Building the markup ...
    html += '</ol>';

    // Show the generated data to the container ...
    container.innerHTML = html;

}

Penggunaan

Sisipkan ID posting/halaman statis setelah path default atau summary:

<div id="result-container">Loading&hellip;</div>
<script>
function generatePostData(json) { … }
</script>
<script src="//nama_blog.blogspot.com/feeds/posts/default/1962799387619194999?alt=json-in-script&callback=generatePostData"></script>

Ekstra

Halaman Statis

Data halaman statis dapat dipanggil dengan menggunakan format URL seperti ini:

http://nama_blog.blogspot.com/feeds/pages/default?alt=json-in-script&orderby=published&callback=generatePostsData
http://nama_blog.blogspot.com/feeds/pages/default?alt=json-in-script&callback=generatePostData

Mode Ringkas

Mode ringkas dapat dipanggil dengan menggunakan format URL seperti ini:

http://nama_blog.blogspot.com/feeds/posts/summary?alt=json-in-script&orderby=published&callback=generatePostsData
http://nama_blog.blogspot.com/feeds/pages/summary?alt=json-in-script&orderby=published&callback=generatePostsData
http://nama_blog.blogspot.com/feeds/posts/summary?alt=json-in-script&callback=generatePostData
http://nama_blog.blogspot.com/feeds/pages/summary?alt=json-in-script&callback=generatePostData
  

Berlangganan

Berlangganan posting: Daftarkan alamat email Anda untuk memperoleh umpan posting terbaru langsung ke kotak masuk pesan.

 21 Komentar

Memuat…

Tautan (link) hidup dalam komentar akan terhapus secara otomatis.
Untuk menyisipkan tautan dengan aman, gunakan kode [url=http://example.com]Teks Tautan[/url]
Untuk menyisipkan kode, gunakan tag <i rel="code">KODE ANDA</i>
Kode yang panjang bisa menggunakan tag <i rel="pre">KODE PANJANG ANDA</i>
Untuk menyisipkan gambar, gunakan kode [img]URL GAMBAR[/img]
Untuk menyisipkan judul, gunakan tag <b rel="h4">JUDUL ANDA DI SINI...</b>
Untuk menciptakan efek tebal gunakan tag <strong>TEKS ANDA DI SINI...</strong>
Untuk menciptakan efek huruf miring gunakan tag <em>TEKS ANDA DI SINI...</em>

Khusus untuk membalas komentar disarankan menggunakan tombol balas di samping komentar terkait dibandingkan menggunakan formulir komentar di bawah agar komunikasi lebih terstruktur. Karena mungkin, apa yang Anda tanyakan/katakan saat ini akan sangat bermanfaat bagi pembaca lain.

:) :( ^_^ :D ;) :-bd :'( :\ :p B) :Q :Ozz 7:( \o/ **p <3 0:) :-a 7:O *fck* x@ X@ ~x( :yaya: =p*

Nama Saya Taufik Nurrohman. Sebenarnya Saya tidak bisa disebut sebagai seorang yang profesional dalam bidang ini, karena Saya tidak menguasai bidang ini melalui pendidikan formal. Saya hanyalah seorang antusias. Dibandingkan sebagai seorang desainer atau pengembang, Saya lebih suka jika disebut sebagai seorang hobiis saja yang tertarik dengan dunia web.

Daftar Tautan

Komunitas

Saya tidak bisa hidup tanpa JavaScript! Aktifkan JavaScript?
Info
  1. http://www.dte.web.id/2013/12/daftar-salinan-berkas-widget-halaman.html
  2. http://www.dte.web.id/2013/02/hosting-file-dengan-google-code-dan.html
Tutup
Ke atas!