Home > Net >  Parsing JSON to get only specific children not all the children
Parsing JSON to get only specific children not all the children

Time:10-17

I have been trying to parse the following JSON data using JSON.Parse(), I only need the url tags inside images not the caption or resizedImageUrls.

{"images": [
            {
                "url": "https://media.IMG_0001.jpg",
                "caption": "Photo1",
                "resizedImageUrls": {
                    "size135x100": "https://media.IMG_0001_135x100.jpg",
                    "size476x317": "https://media.IMG_0001_476x317.jpg",
                    "size656x437": "https://media.IMG_0001_656x437.jpg"
                }
            },
            {
                "url": "https://media.IMG_0002.jpg",
                "caption": "Photo2",
                "resizedImageUrls": {
                    "size135x100": "https://media.IMG_0002_135x100.jpg",
                    "size476x317": "https://media.IMG_0002_476x317.jpg",
                    "size656x437": "https://media.IMG_0002_656x437.jpg"
                }
            },{
                "url": "https://media.IMG_0003.jpg",
                "caption": "Photo3",
                "resizedImageUrls": {
                    "size135x100": "https://media.IMG_0003_135x100.jpg",
                    "size476x317": "https://media.IMG_0003_476x317.jpg",
                    "size656x437": "https://media.IMG_0003_656x437.jpg"
                }
            }
        ]}

I declared the above JSON as variable data and then used following code.

var items = JSON.parse(data);
return {
    url: items.images;
}

But it returned all the urls, captions and resized image urls. I know another method is to use items.images[0].url. But, sometimes there are lots of image urls and its not feasible to add codes from 0 to n numbers. I thought about using for loop, but, I dont know how.

CodePudding user response:

You can make a map and return urls only.

const items = JSON.parse(data);
const urls = items.images.map(item => item.url);
  • Related