簡體   English   中英

jQuery多維JSON數組在同一JSON中具有不同的數據?

[英]jQuery multidimensional JSON array with different data in the same JSON?

這有點難以解釋,但我會盡力進行解釋,以便我能獲得一些幫助,並希望有人能對此問題有所啟發。

基本上,我有一個看起來像這樣的JSON:

    "created_at": "Sun Apr 09 17:56:20 +0000 2017",
    "id": 851131679167139842,
    "id_str": "851131679167139842",
    "text": "hello world with an image goes here as a test! https:\/\/t.co\/jNfdESxPcn",
    "truncated": false,
    "entities": {
        "hashtags": [],
        "symbols": [],
        "user_mentions": [],
        "urls": [],
        "media": [{
            "id": 851131665623732225,
            "id_str": "851131665623732225",
            "indices": [47, 70],
            "media_url": "http:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
            "media_url_https": "https:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
            "url": "https:\/\/t.co\/jNfdESxPcn",
            "display_url": "pic.twitter.com\/jNfdESxPcn",
            "expanded_url": "https:\/\/twitter.com\/DavidHoperz\/status\/851131679167139842\/photo\/1",
            "type": "photo",
            "sizes": {
                "thumb": {
                    "w": 150,
                    "h": 150,
                    "resize": "crop"
                },
                "large": {
                    "w": 670,
                    "h": 728,
                    "resize": "fit"
                },
                "small": {
                    "w": 626,
                    "h": 680,
                    "resize": "fit"
                },
                "medium": {
                    "w": 670,
                    "h": 728,
                    "resize": "fit"
                }
            }
        }]
    },
    "extended_entities": {
        "media": [{
            "id": 851131665623732225,
            "id_str": "851131665623732225",
            "indices": [47, 70],
            "media_url": "http:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
            "media_url_https": "https:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
            "url": "https:\/\/t.co\/jNfdESxPcn",
            "display_url": "pic.twitter.com\/jNfdESxPcn",
            "expanded_url": "https:\/\/twitter.com\/DavidHoperz\/status\/851131679167139842\/photo\/1",
            "type": "photo",
            "sizes": {
                "thumb": {
                    "w": 150,
                    "h": 150,
                    "resize": "crop"
                },
                "large": {
                    "w": 670,
                    "h": 728,
                    "resize": "fit"
                },
                "small": {
                    "w": 626,
                    "h": 680,
                    "resize": "fit"
                },
                "medium": {
                    "w": 670,
                    "h": 728,
                    "resize": "fit"
                }
            }
        }]
    },
    "source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    "user": {
        "id": 851119985732800513,
        "id_str": "851119985732800513",
        "name": "David",
        "screen_name": "DavidHoperz",
        "location": "",
        "description": "",
        "url": null,
        "entities": {
            "description": {
                "urls": []
            }
        },
        "protected": false,
        "followers_count": 0,
        "friends_count": 21,
        "listed_count": 0,
        "created_at": "Sun Apr 09 17:09:52 +0000 2017",
        "favourites_count": 0,
        "utc_offset": null,
        "time_zone": null,
        "geo_enabled": false,
        "verified": false,
        "statuses_count": 3,
        "lang": "en",
        "contributors_enabled": false,
        "is_translator": false,
        "is_translation_enabled": false,
        "profile_background_color": "F5F8FA",
        "profile_background_image_url": null,
        "profile_background_image_url_https": null,
        "profile_background_tile": false,
        "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_link_color": "1DA1F2",
        "profile_sidebar_border_color": "C0DEED",
        "profile_sidebar_fill_color": "DDEEF6",
        "profile_text_color": "333333",
        "profile_use_background_image": true,
        "has_extended_profile": false,
        "default_profile": true,
        "default_profile_image": false,
        "following": false,
        "follow_request_sent": false,
        "notifications": false,
        "translator_type": "none"
    },
    "geo": null,
    "coordinates": null,
    "place": null,
    "contributors": null,
    "is_quote_status": false,
    "retweet_count": 0,
    "favorite_count": 0,
    "favorited": false,
    "retweeted": false,
    "possibly_sensitive": false,
    "lang": "en"
}, {
    "created_at": "Sun Apr 09 17:47:36 +0000 2017",
    "id": 851129482832470026,
    "id_str": "851129482832470026",
    "text": "How to display twitter posts using javascript https:\/\/t.co\/I49vjVbAUJ",
    "truncated": false,
    "entities": {
        "hashtags": [],
        "symbols": [],
        "user_mentions": [],
        "urls": [{
            "url": "https:\/\/t.co\/I49vjVbAUJ",
            "expanded_url": "https:\/\/www.script-tutorials.com\/how-to-display-twitter-posts-using-javascript\/",
            "display_url": "script-tutorials.com\/how-to-display\u2026",
            "indices": [46, 69]
        }]
    },
    "source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    "user": {
        "id": 851119985732800513,
        "id_str": "851119985732800513",
        "name": "David",
        "screen_name": "DavidHoperz",
        "location": "",
        "description": "",
        "url": null,
        "entities": {
            "description": {
                "urls": []
            }
        },
        "protected": false,
        "followers_count": 0,
        "friends_count": 21,
        "listed_count": 0,
        "created_at": "Sun Apr 09 17:09:52 +0000 2017",
        "favourites_count": 0,
        "utc_offset": null,
        "time_zone": null,
        "geo_enabled": false,
        "verified": false,
        "statuses_count": 3,
        "lang": "en",
        "contributors_enabled": false,
        "is_translator": false,
        "is_translation_enabled": false,
        "profile_background_color": "F5F8FA",
        "profile_background_image_url": null,
        "profile_background_image_url_https": null,
        "profile_background_tile": false,
        "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_link_color": "1DA1F2",
        "profile_sidebar_border_color": "C0DEED",
        "profile_sidebar_fill_color": "DDEEF6",
        "profile_text_color": "333333",
        "profile_use_background_image": true,
        "has_extended_profile": false,
        "default_profile": true,
        "default_profile_image": false,
        "following": false,
        "follow_request_sent": false,
        "notifications": false,
        "translator_type": "none"
    },
    "geo": null,
    "coordinates": null,
    "place": null,
    "contributors": null,
    "is_quote_status": false,
    "retweet_count": 2,
    "favorite_count": 1,
    "favorited": false,
    "retweeted": false,
    "possibly_sensitive": false,
    "lang": "en"
}, {
    "created_at": "Sun Apr 09 17:33:43 +0000 2017",
    "id": 851125986976567297,
    "id_str": "851125986976567297",
    "text": "Hello world",
    "truncated": false,
    "entities": {
        "hashtags": [],
        "symbols": [],
        "user_mentions": [],
        "urls": []
    },
    "source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
    "in_reply_to_status_id": null,
    "in_reply_to_status_id_str": null,
    "in_reply_to_user_id": null,
    "in_reply_to_user_id_str": null,
    "in_reply_to_screen_name": null,
    "user": {
        "id": 851119985732800513,
        "id_str": "851119985732800513",
        "name": "David",
        "screen_name": "DavidHoperz",
        "location": "",
        "description": "",
        "url": null,
        "entities": {
            "description": {
                "urls": []
            }
        },
        "protected": false,
        "followers_count": 0,
        "friends_count": 21,
        "listed_count": 0,
        "created_at": "Sun Apr 09 17:09:52 +0000 2017",
        "favourites_count": 0,
        "utc_offset": null,
        "time_zone": null,
        "geo_enabled": false,
        "verified": false,
        "statuses_count": 3,
        "lang": "en",
        "contributors_enabled": false,
        "is_translator": false,
        "is_translation_enabled": false,
        "profile_background_color": "F5F8FA",
        "profile_background_image_url": null,
        "profile_background_image_url_https": null,
        "profile_background_tile": false,
        "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
        "profile_link_color": "1DA1F2",
        "profile_sidebar_border_color": "C0DEED",
        "profile_sidebar_fill_color": "DDEEF6",
        "profile_text_color": "333333",
        "profile_use_background_image": true,
        "has_extended_profile": false,
        "default_profile": true,
        "default_profile_image": false,
        "following": false,
        "follow_request_sent": false,
        "notifications": false,
        "translator_type": "none"
    },
    "geo": null,
    "coordinates": null,
    "place": null,
    "contributors": null,
    "is_quote_status": false,
    "retweet_count": 0,
    "favorite_count": 0,
    "favorited": false,
    "retweeted": false,
    "lang": "en"
}]

我有一個jQuery來讀取看起來像這樣的JSON數據:

var poutput = $('.listHolder');

$.ajax({
    url: 'page.php',
    dataType: 'json',
    timeout: 5000,
    success: function(data){
        $.each(data, function(pi,item){ 
            str = item.id_str;

            var products = '<div id="'+item.id_str+'" class="items">'+
                '<p class="names">'+item.created_at+'</p>'+
                '<p class="names">'+item.text+'</p>'+
                '<img src="'+item.entities.media[0].media_url_https+'" width="100%">'+
                '</div>';
            console.log(products);
            poutput.append(products);
        });
    },
    error: function(){
        //alert('There was an error loading the data.');
    }
});

如果查看JSON數據( 上面的第一個代碼 ),您將看到其中一些數據具有media_url_https而某些則沒有。

這引起了我一個問題,因為當我嘗試使用上面的jQuery代碼獲取所有JSON數據時,它將僅獲取其中包含media_url_https的數據,而IGNORES則獲取其他不具有media_url_https

但是,當我從代碼中刪除'<img src="'+item.entities.media[0].media_url_https+'" width="100%">'+ ,它將獲得所有數據,但不會有任何圖像(圖像也是必需的)!

有什么辦法可以從JSON數據中獲取所有數據,包括圖像等?

我希望這是有道理的,有人可以幫助我解決此問題。

任何幫助,將不勝感激。

編輯:

這是我嘗試使用if()和else()語句的方式:

        $.each(data, function(pi,item){ 
            str = item.id_str;  

        var media ="";

        var mediaUrl = item.entities.media[0].media_url_https;

        if(mediaUrl !=''){

        media = '<img src="'+item.entities.media[0].media_url_https+'" width="100%">';

        }else{
        media = '';

        }


            //alert(item.entities.media[0].media_url_https);
               var products = '<div id="'+item.id_str+'" class="items">'+
                               '<p class="names">'+item.text+'</p>'+
                                media+
                               '</div>';


///reset of my code........

由於所有items都具有一個entities屬性,但是只有一些entities具有media屬性, media_url_https在使用它來構建html字符串之前,應檢查該media屬性及其所有子屬性的存在,直到media_url_https ,即:

if (item.entities.media 
  && item.entities.media.length 
  && item.entities.media[0].media_url_https) {
  // code to add image to html string
}

根據我對您的問題和評論的了解:您想知道給定一個對象可能具有或不具有某些屬性,我該如何解釋不存在的屬性? 特別是您的img。

如注釋中所述,您可以為某些屬性編寫條件以填充值(如果它們不存在),並且仍應遍歷所有數據。

一種方法我想建議的默認值是JavaScript的利用率truthy功能,使我們能夠把常規的變量有點像布爾值。

var products = '<div id="'+item.id_str+'" class="items">'+
            '<p class="names">'+item.created_at+'</p>'+
            '<p class="names">'+item.text+'</p>'+
            '<img src="'+(item.entities.media[0].media_url_https || "./img/default_img.png")+'" width="100%">'+
            '</div>';

在這段代碼中,我利用了JavaScript中的每個值都具有“真實”或“虛假”值的事實,並且使用布爾值或運算符,我實際上可以將“虛假”值合並為“真實”默認值。

用簡單的英語來說,我更改的行將遵循“使用item.entities.media[0].media_url_https如果其值存在且不為空,否則使用"./img/default_img.png"

如果不清楚,您可以將"./img/default_img.png"更改為"./img/default_img.png"任何內容,另一個變量,不同的字符串常量等。

我喜歡使用像這樣的真實評估,因為它有助於保持代碼相當干凈,並且確實節省了空間和需要發送到瀏覽器的數據量(即使數量可忽略不計)。

根據詹姆斯的評論,這就像一個魅力。

    var poutput = $('.listHolder');

    $.ajax({
    url: 'PAGE.php',
        dataType: 'json',
        timeout: 5000,
        success: function(data){




        $.each(data, function(pi,item){ 


        if (item.entities.media && item.entities.media.length && item.entities.media[0].media_url_https){



        var media = '<img src="'+item.entities.media[0].media_url_https+'" width="100%">';
        var products = '<div id="'+item.id_str+'" class="items">'+
                       '<p class="names">'+item.text+'</p>'+
                        media+
                        '</div>';

        }else{



        var products = '<div id="'+item.id_str+'" class="items">'+
                       '<p class="names">'+item.text+'</p>'+
                        '</div>';
        }






               console.log(products);

                poutput.append(products);




});


},

        error: function(){
            //alert('There was an error loading the data.');
        }


});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM