简体   繁体   中英

Grab data from JSON using JSON data as var

I trying to grab the url of an attached photo using json. Im using the value of the data from the json "HousePhoto1". I then want to use that value to grab the value from the post_media data. This is what im using at the moment, but my javascript doesn't load correctly when I try this, but if i take to .guid away, my page loads but without any json data. I have also added a photo of my json.

    $.getJSON( "https://example.co.uk/wp-json/wp/v2/posts?&per_page=1&page=1", function( data ) {
      $.each( data, function( key, val ) {
        var photo = val.post_media[val.HousePhoto1].guid;
      });

    });

<img src="'+photo+'"/>

Image of my json

You were almost there. However, it looks like you are receiving an array back from your JSON response. Using a simplified dataset as my example, you can probably do something like this:

var data = [
  {
    HousePhoto1: "7073",
    post_media: {
      7073: {
        guid: "https://somecoolphoto.com"
      }
    }
  },
  {
    HousePhoto1: "7085",
    post_media: {
      7085: {
        guid: "https://anothercoolphoto.com"
      }
    }
  },
];

$.each(data, function(index, value) {
 var housePhotoId = value.HousePhoto1;
 var photo = value.post_media[housePhotoId].guid;
});

Also, if you are attempting to set multiple images, you cannot do it the way you currently are. You should dynamically insert the image into the DOM inside each iteration of the each loop via JavaScript.

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