How can I get YouTube channel ID using channel name URL? - javascript

I have made a program where users provide a YouTube channel URL and in return I will show the user its channel ID.
Like if someone puts URL like: https://youtube.com/#AndreoBee then I will return its channel ID.
const axios = require('axios');
async function getChannelId(url) {
const channelUsername = url.split('/').pop();
const response = await axios.get(`https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=${channelUsername}&key=myapi`);
if (response.data.items.length === 0) {
throw new Error(`Channel not found: ${url}`);
}
console.log(response.data.items[0].id);
}
getChannelId('https://www.youtube.com/#AndreoBee');
Output:
/home/runner/ytcheck/index.js:7 if (response.data.items.length ===
0) {
^
TypeError: Cannot read properties of undefined (reading 'length')
at getChannelId (/home/runner/ytcheck/index.js:7:27)

One alternative - using YouTube Data API - could be:
Use the search:list endpoint for search channels that matches with the criteria - in this case, the name/handle of the channel.
Example:
Search channels named "AndreoBee" - you're getting this value in the channelUsername variable in your code:
URL:
https://youtube.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=10&q=AndreoBee&type=channel&key=[YOUR_API_KEY]
Response:
{
"kind": "youtube#searchListResponse",
"etag": "K2G-sXJIFnrJFyMaoDvw4XMBym4",
"nextPageToken": "CAoQAA",
"regionCode": "CO",
"pageInfo": {
"totalResults": 6740,
"resultsPerPage": 10
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "oeyNublAqxB8TOEQbtwA4k0Oqgs",
"id": {
"kind": "youtube#channel",
"channelId": "UCjdjyjdcdmldCK5XuuWbn1A"
},
"snippet": {
"publishedAt": "2020-01-21T15:12:27Z",
"channelId": "UCjdjyjdcdmldCK5XuuWbn1A",
"title": "AndreoBee",
"description": "I am a Youtuber.",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJW_gCXDGAviuBWh0GwUO4V5Ia4JNYzC0Mp9bYhigA=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJW_gCXDGAviuBWh0GwUO4V5Ia4JNYzC0Mp9bYhigA=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJW_gCXDGAviuBWh0GwUO4V5Ia4JNYzC0Mp9bYhigA=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2020-01-21T15:12:27Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "iG8-NwZab0LLB245AY2MkJ6pexI",
"id": {
"kind": "youtube#channel",
"channelId": "UC2Xpzteb9hbamaeEHZRxPCw"
},
"snippet": {
"publishedAt": "2020-11-27T07:07:23Z",
"channelId": "UC2Xpzteb9hbamaeEHZRxPCw",
"title": "AndreoBee",
"description": "This is my backup channel guys ;)",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJVgMinAIKpEHBPjM2Os8fHFKcsxtTyTIflqTwVR=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJVgMinAIKpEHBPjM2Os8fHFKcsxtTyTIflqTwVR=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJVgMinAIKpEHBPjM2Os8fHFKcsxtTyTIflqTwVR=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2020-11-27T07:07:23Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "3X2zApHnPAW2p2awm4tIETn9ybI",
"id": {
"kind": "youtube#channel",
"channelId": "UCp6iawa7GPTszoJxOiG5d_Q"
},
"snippet": {
"publishedAt": "2021-03-15T16:19:39Z",
"channelId": "UCp6iawa7GPTszoJxOiG5d_Q",
"title": "AndreoBee",
"description": "Welcome my ARS GAMING YouTube channel I am uploading full movies or shorts and how to download movies on my YouTube ...",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/Z2CC1zWbsD3k-z9cX0RlPBstKELZw0_sUgFPggIt-DhVkJWL8iJG8pCLizxr3StB8lbZX9PT7U8=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/Z2CC1zWbsD3k-z9cX0RlPBstKELZw0_sUgFPggIt-DhVkJWL8iJG8pCLizxr3StB8lbZX9PT7U8=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/Z2CC1zWbsD3k-z9cX0RlPBstKELZw0_sUgFPggIt-DhVkJWL8iJG8pCLizxr3StB8lbZX9PT7U8=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2021-03-15T16:19:39Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "VHP4HsDcIiETPleAWN0cSC7fvbE",
"id": {
"kind": "youtube#channel",
"channelId": "UCWLY3sMMYHH3-9xQ2lhFj8g"
},
"snippet": {
"publishedAt": "2022-06-27T01:08:10Z",
"channelId": "UCWLY3sMMYHH3-9xQ2lhFj8g",
"title": "AndreoBee",
"description": "Hii guus i am Andreo I hope you like my videos and please support me guys thank you have a good day.",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/bHaKoA8QZnZSJXfmK7udtrzxmpCOOhpTHIoP_RQUD2KLv9qNXtLLKY_bewbaQGdfZGIPCcO9Ag=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/bHaKoA8QZnZSJXfmK7udtrzxmpCOOhpTHIoP_RQUD2KLv9qNXtLLKY_bewbaQGdfZGIPCcO9Ag=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/bHaKoA8QZnZSJXfmK7udtrzxmpCOOhpTHIoP_RQUD2KLv9qNXtLLKY_bewbaQGdfZGIPCcO9Ag=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2022-06-27T01:08:10Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "01NvBqsdnNimHwnwHnGkeVOhJ-8",
"id": {
"kind": "youtube#channel",
"channelId": "UC3yVv5tuR3tBcVf97j33mQQ"
},
"snippet": {
"publishedAt": "2020-12-12T14:31:22Z",
"channelId": "UC3yVv5tuR3tBcVf97j33mQQ",
"title": "Andreobee",
"description": "Describe the game All best game for play on Android in 2GB ram and 3GB phone.",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJXval25GhQFpbqoFgQXvWBol5aqf4ZCOluMMOe-=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJXval25GhQFpbqoFgQXvWBol5aqf4ZCOluMMOe-=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJXval25GhQFpbqoFgQXvWBol5aqf4ZCOluMMOe-=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "Andreobee",
"liveBroadcastContent": "none",
"publishTime": "2020-12-12T14:31:22Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "B5TOx4aFyuua9eQVa-QBbKDjIng",
"id": {
"kind": "youtube#channel",
"channelId": "UCBR0QlbTtbT52oFmmDZIamw"
},
"snippet": {
"publishedAt": "2022-02-01T14:44:18Z",
"channelId": "UCBR0QlbTtbT52oFmmDZIamw",
"title": "AndreoBee",
"description": "",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/TfGkwtvsAvJdWnMOdRLRn2HKRvnVj872dxLZdZ_ghFwpF4SrY2BqBwJ3syc1V6HLL3LyJiSABQ=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/TfGkwtvsAvJdWnMOdRLRn2HKRvnVj872dxLZdZ_ghFwpF4SrY2BqBwJ3syc1V6HLL3LyJiSABQ=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/TfGkwtvsAvJdWnMOdRLRn2HKRvnVj872dxLZdZ_ghFwpF4SrY2BqBwJ3syc1V6HLL3LyJiSABQ=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2022-02-01T14:44:18Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "t04J8v3aRhQhmFsyv54ddTXGDMQ",
"id": {
"kind": "youtube#channel",
"channelId": "UCBvdbv05Cb4Ulf_PlunMJtA"
},
"snippet": {
"publishedAt": "2021-08-12T06:59:40Z",
"channelId": "UCBvdbv05Cb4Ulf_PlunMJtA",
"title": "AndreoBee",
"description": "",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/S3J1R-s_P481lUpBULskSiQ0Pv-Z_iLnE_YrZ10OL1cydCFx6a1aOXvRJskMxY-gVpa8cqwuzQ=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/S3J1R-s_P481lUpBULskSiQ0Pv-Z_iLnE_YrZ10OL1cydCFx6a1aOXvRJskMxY-gVpa8cqwuzQ=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/S3J1R-s_P481lUpBULskSiQ0Pv-Z_iLnE_YrZ10OL1cydCFx6a1aOXvRJskMxY-gVpa8cqwuzQ=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2021-08-12T06:59:40Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "dmhfSWj6r1CzXr4yopXkorSsVL0",
"id": {
"kind": "youtube#channel",
"channelId": "UCvXV0HSenVdIpdAuogNPuOQ"
},
"snippet": {
"publishedAt": "2022-11-02T12:01:42Z",
"channelId": "UCvXV0HSenVdIpdAuogNPuOQ",
"title": "AndreoBee",
"description": "PLZ SUB.....",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/NfH1RxDcGEbLe8cOoi7VwFz-dfUcAToV-84rag4x1CIQM8GSnZirguR5SI30M3bZnMP80tA=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/NfH1RxDcGEbLe8cOoi7VwFz-dfUcAToV-84rag4x1CIQM8GSnZirguR5SI30M3bZnMP80tA=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/NfH1RxDcGEbLe8cOoi7VwFz-dfUcAToV-84rag4x1CIQM8GSnZirguR5SI30M3bZnMP80tA=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBee",
"liveBroadcastContent": "none",
"publishTime": "2022-11-02T12:01:42Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "c5Y3zUOZKiyJ-pI7mrLdi4WPegc",
"id": {
"kind": "youtube#channel",
"channelId": "UCmrR9PVxSVRLdp2HK_xP2yA"
},
"snippet": {
"publishedAt": "2021-09-13T06:16:47Z",
"channelId": "UCmrR9PVxSVRLdp2HK_xP2yA",
"title": "ANDREOBEE",
"description": "AndreoBee fan Club For business inquiries ANDREOBEEofficial.",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/CtsMEUKLJC5apm5bX7vEr_3g7nIJn-GfjLodWXLVLF-jFGfyXhFBTiLUvOU8l51e3kVPph5MUQ=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/CtsMEUKLJC5apm5bX7vEr_3g7nIJn-GfjLodWXLVLF-jFGfyXhFBTiLUvOU8l51e3kVPph5MUQ=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/CtsMEUKLJC5apm5bX7vEr_3g7nIJn-GfjLodWXLVLF-jFGfyXhFBTiLUvOU8l51e3kVPph5MUQ=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "ANDREOBEE",
"liveBroadcastContent": "none",
"publishTime": "2021-09-13T06:16:47Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "-lb0jmjUJcQsLJDGHH7KVs14-nU",
"id": {
"kind": "youtube#channel",
"channelId": "UCvqm9nqHYYehmq7FcorjS4Q"
},
"snippet": {
"publishedAt": "2021-01-13T05:54:00Z",
"channelId": "UCvqm9nqHYYehmq7FcorjS4Q",
"title": "AndreoBEE",
"description": "",
"thumbnails": {
"default": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJUIkodf8aTOx2ZcNoyycMHQqgqNvehuXN_iz9Ii=s88-c-k-c0xffffffff-no-rj-mo"
},
"medium": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJUIkodf8aTOx2ZcNoyycMHQqgqNvehuXN_iz9Ii=s240-c-k-c0xffffffff-no-rj-mo"
},
"high": {
"url": "https://yt3.ggpht.com/ytc/AL5GRJUIkodf8aTOx2ZcNoyycMHQqgqNvehuXN_iz9Ii=s800-c-k-c0xffffffff-no-rj-mo"
}
},
"channelTitle": "AndreoBEE",
"liveBroadcastContent": "none",
"publishTime": "2021-01-13T05:54:00Z"
}
}
]
}
N.B: for this case, I will accept that the first result is the channel I'm looking for, however, notice here that you might get more than one channel that matches the channel name.
For detect which one of the results of the search matches with the channel you're looking for, you could then, make a request to the channel:list endpoint - by passing the channel_id of the search result - and see their customUrl value and/or check the channel that has more videos/subscribers/etc.
Check my answer for more info.

You can get a channel id using /search Youtube API. Instead using this :
https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=${channelUsername}&key=myapi
Try with this endpoint :
https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=${channelUsername}&type=channel&key=myapi

Related

How can I take the data from choiceSet in adaptive cards

I want the data (i.e value inside choices array) inside the red choiseSet when selected and clicked on the btn, I kept an image and added action submit as action.submit as that's my usecase, I am pretty much confused how I can do that, Here's the card payload
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "Input.ChoiceSet",
"id": "myColor2",
"style": "expanded",
"value": "1",
"choices": [
{
"title": "Red",
"value": "1"
}
]
},
{
"type": "Image",
"altText": "it's a image",
"url": "https://media.istockphoto.com/vectors/bhutanese-ngultrum-btn-vector-id1304476894",
"width": "100px",
"height": "100px",
"horizontalAlignment": "Left",
"selectAction": {
"type": "Action.Submit",
"id": "btn",
"title": "btn"
}
}
]
}
Once submitted by clicking on the icon, the bot should receive an activity of type message but with no text. The data you want is in the value property.
{
"activity": {
"channelData": {
"postBack": true,
"clientActivityID": "<REMOVED>",
"clientTimestamp": "2022-04-05T18:43:17.348Z"
},
"type": "message",
"value": {
"myColor2": "1"
},
"channelId": "emulator",
"from": {
"id": "<REMOVED>",
"name": "",
"role": "user"
},
"locale": "en-us",
"localTimestamp": "2022-04-05T11:43:17-07:00",
"localTimezone": "America/Los_Angeles",
"timestamp": "2022-04-05T18:43:17.408Z",
"id": "<REMOVED>",
"recipient": {
"id": "<REMOVED>",
"name": "Bot",
"role": "bot"
},
"conversation": {
"id": "<REMOVED>"
},
"serviceUrl": "http://localhost:3212"
},
"id": "<REMOVED>",
"timestamp": 1649184197408
}

JS array to tree by path

this is my first post ever here. I'm trying to make tree from array of objects by path. I'm unable to get second file into the same folder, folders can be nested infinitely. I'm a bit desperate, this is bugging me for a while...
The array: https://textuploader.com/149ku
let result = [];
let level = { result };
notes.forEach(note => {
const pathSplit = note.path.split('/');
pathSplit.reduce((r, name, i, a) => {
if (!r[name]) {
if (i === pathSplit.length - 1) {
r[name] = { result: [{name: note.title}] };
r.result.push({ name, children: r[name].result });
}
else {
r[name] = { result: [] };
r.result.push({ name, children: r[name].result });
}
}
else {
// What's here?
}
return r[name];
}, level)
});
This is how react render looks:
const treeItems = nodes => {
if(nodes){
return nodes.map((node, index) =>{
return (
<NoteTreeItem style={{paddingLeft: '8px'}} key={index} nodeId={(Math.random()).toString()} labelText={node.name} labelIcon={FolderIcon}>
{Array.isArray(node.children[0].children) ?
node.children.map(child => treeItems([child])) :
<NoteTreeItem saveEditNoteHandle={saveEditNoteHandle} note={node.children[0]} key={Math.random()} nodeId={Math.random().toString()}
labelText={node.children[0].name} labelIcon={DescriptionIcon} />}
</NoteTreeItem>)
});
}
};
Missing file
EDIT: React code is not relevant
To write straightforward paths like: Idk.neco.neco, it can be for example:
const root = {};
notes.forEach((note, i) => {
const folders = note.path.split('/');
folders.reduce((folder, folderName, i, arr) => {
// use prefix/suffix char that cant be contained in path to prevent overwriting
folder[folderName] = folder[folderName] || {_name: folderName, _children: []}
if (i === (arr.length - 1)) {
folder[folderName]._children.push(note);
}
return folder[folderName]
}, root)
})
console.log(root.Idk.neco.neco)
<script>
var notes =[
{
"check": false,
"createdAt": "2020-03-14T06:30:36.259Z",
"_id": "5e6c7a0c8506272230e0ab64",
"title": "Firewall",
"desc": "1) Update\n2) Allow ports\n3) chmod shortcuts\n4) bash\n5) something\n6) something else",
"tag": "Work",
"path": "sysadmin/linux",
"remindDate": "2020-03-20T00:00:00.000Z"
},
{
"check": true,
"createdAt": "2020-03-14T06:31:56.999Z",
"_id": "5e6c7a5c8506272230e0ab65",
"title": "Garden work",
"desc": "Help her with garden work and with cooking",
"tag": "Life",
"path": "Help/Mom",
"remindDate": "2020-03-17T00:00:00.000Z"
},
{
"check": true,
"createdAt": "2020-03-14T06:32:40.738Z",
"_id": "5e6c7a888506272230e0ab66",
"title": "Learn Stocks",
"desc": "When to buy/sell and how to predict",
"tag": "Business",
"path": "Money/stocks",
"remindDate": "2020-03-19T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-14T06:34:44.629Z",
"_id": "5e6c7b048506272230e0ab69",
"title": "Kombinatorika",
"desc": "Permutace",
"tag": "School",
"path": "Math class/something/another subfolder/topic",
"remindDate": "2020-04-21T00:00:00.000Z"
},
{
"check": true,
"createdAt": "2020-03-14T06:34:58.273Z",
"_id": "5e6c7b128506272230e0ab6a",
"title": "Posloupnost",
"desc": "Geometricka a neco",
"tag": "Work",
"path": "Math class/something/something/different subfolder/topic",
"remindDate": "2020-04-16T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-14T06:37:34.568Z",
"_id": "5e6c7bae8506272230e0ab6b",
"title": "FTP server",
"desc": "Allow group A and B to access FTP",
"tag": "Work",
"path": "sysadmin/windows",
"remindDate": "2020-04-14T00:00:00.000Z"
},
{
"check": true,
"createdAt": "2020-03-15T05:29:29.345Z",
"_id": "5e6dbd398c496347ac5e1010",
"title": "PC",
"desc": "Run antivirus",
"tag": "Life",
"path": "Help/Dad",
"remindDate": "2020-04-04T00:00:00.000Z"
},
{
"check": true,
"createdAt": "2020-03-17T09:11:20.558Z",
"_id": "5e70943831441216a49faae4",
"title": "2021",
"desc": "2021",
"tag": "No category",
"path": "No category",
"remindDate": "2021-03-17T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-17T18:53:46.443Z",
"_id": "5e711cba9f3edb19a41ca77a",
"title": "17",
"desc": "17",
"tag": "No category",
"path": "17",
"remindDate": "2020-03-17T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-19T08:20:53.237Z",
"_id": "5e732b65a059104a01e0c510",
"title": "20",
"desc": "20",
"tag": "Life",
"path": "20",
"remindDate": "2020-03-20T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-19T19:02:28.373Z",
"_id": "5e73c1c4129dc33e68995634",
"title": "not 20",
"desc": "not 20",
"tag": "School",
"path": "20",
"remindDate": "2020-03-17T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-21T07:18:44.770Z",
"_id": "5e75bfd4baa9fc431475ed7b",
"title": "VIM",
"desc": "learn vim/vi :D",
"tag": "School",
"path": "sysadmin/linux",
"remindDate": "2020-03-28T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-03-25T07:31:24.943Z",
"_id": "5e7b08cc3d441b1f263304ee",
"title": "Sometging",
"desc": "Ckntent\n\n\n",
"tag": "Life",
"path": "Idk/neco/neco",
"remindDate": "2020-03-26T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-04-04T15:07:45.435Z",
"_id": "5e88a2c134a35d05568ac15a",
"title": "first file",
"desc": "first file",
"tag": "No category",
"path": "twofiles/folder",
"remindDate": "2020-04-30T00:00:00.000Z"
},
{
"check": false,
"createdAt": "2020-04-04T15:07:58.312Z",
"_id": "5e88a2ce34a35d05568ac15b",
"title": "second file",
"desc": "second file",
"tag": "No category",
"path": "twofiles/folder",
"remindDate": "2020-05-02T00:00:00.000Z"
},
];
</script>

JavaScript: parsing JSON

I parsed this JSON:
foobar({
"kind": "youtube#searchListResponse",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/pHRM7wJ9wmWClTcY53S4FP4-Iho\"",
"nextPageToken": "CAUQAA",
"regionCode": "PL",
"pageInfo": {
"totalResults": 686,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"I_8xdZu766_FSaexEaDXTIfEWc0/hpaieEHTq-SS7i8XR2SdBPqendk\"",
"id": {
"kind": "youtube#video",
"videoId": "j6r_N251pNQ"
}, "width": 480,
"height": 360
}
},
"channelTitle": "arhn.eu",
"liveBroadcastContent": "none"
}
},
My code (json_string contains the above JSON):
var json = JSON.parse(JSON.stringify(json_string));
alert(json['foobar']);
How can I get videoId value?
You can reach it with:
json['foobar']['items']['id']['videoId']
Just nest it :)

How to loop inside a json file with javascript?

I have a json file returned on my javascript code. The file looks like this :
{
"data": [
{
"id": "594984240522886",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Ducks",
"description": "ducks",
"link": "http://www.facebook.com/album.php?fbid=594984240522886&id=593959083958735&aid=1073741834",
"cover_photo": "594984260522884",
"count": 4,
"type": "normal",
"created_time": "2013-06-13T15:12:22+0000",
"updated_time": "2013-06-13T15:12:40+0000",
"can_upload": false
},
{
"id": "593963787291598",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Profile Pictures",
"link": "http://www.facebook.com/album.php?fbid=593963787291598&id=593959083958735&aid=1073741832",
"cover_photo": "593963797291597",
"count": 1,
"type": "profile",
"created_time": "2013-06-11T16:52:29+0000",
"updated_time": "2013-06-11T16:52:31+0000",
"can_upload": false
},
{
"id": "593963467291630",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Goats",
"description": "goats",
"link": "http://www.facebook.com/album.php?fbid=593963467291630&id=593959083958735&aid=1073741831",
"cover_photo": "593963477291629",
"count": 7,
"type": "normal",
"created_time": "2013-06-11T16:51:56+0000",
"updated_time": "2013-06-11T16:52:02+0000",
"can_upload": false
},
{
"id": "593962700625040",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Dogs",
"description": "dogs",
"link": "http://www.facebook.com/album.php?fbid=593962700625040&id=593959083958735&aid=1073741830",
"cover_photo": "593962710625039",
"count": 10,
"type": "normal",
"created_time": "2013-06-11T16:50:27+0000",
"updated_time": "2013-06-11T16:50:37+0000",
"can_upload": false
},
{
"id": "593961937291783",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Cows",
"description": "Cows",
"link": "http://www.facebook.com/album.php?fbid=593961937291783&id=593959083958735&aid=1073741829",
"cover_photo": "593961983958445",
"count": 5,
"type": "normal",
"created_time": "2013-06-11T16:48:26+0000",
"updated_time": "2013-06-11T16:49:32+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NTkzOTYxOTM3MjkxNzgz",
"before": "NTk0OTg0MjQwNTIyODg2"
}
}
}
I would like to loop inside the "data" and see how many different data elements exist(as you see each element has an id , from , name , description..) . How can i do that with javascript?
You can try the following code:
for(i=0;json.data.length;i++){
var element = json.data[i];
}
or also in this other way:
for (i in json.data) {
if (json.data.hasOwnProperty(i)) {
var element = json.data[i];
}
}

Accessing data in json?

I want to get some elements from json response from youtube api:
I get this response in my script:
{
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$media": "http://search.yahoo.com/mrss/",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$gd": "http://schemas.google.com/g/2005",
"xmlns$yt": "http://gdata.youtube.com/schemas/2007",
"id": {
"$t": "http://gdata.youtube.com/feeds/api/videos"
},
"updated": {
"$t": "2013-01-13T15:48:18.863Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://gdata.youtube.com/schemas/2007#video"
}
],
"title": {
"$t": "Videos matching: humor",
"type": "text"
},
"logo": {
"$t": "http://www.youtube.com/img/pic_youtubelogo_123x63.gif"
},
"link": [
{
"rel": "alternate",
"type": "text/html",
"href": "http://www.youtube.com"
},
{
"rel": "http://schemas.google.com/g/2005#feed",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos"
},
{
"rel": "http://schemas.google.com/g/2005#batch",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos/batch"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos?alt=json&q=humor&start-index=1&max-results=1&lr=es&orderby=published"
},
{
"rel": "next",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos?alt=json&q=humor&start-index=2&max-results=1&lr=es&orderby=published"
}
],
"author": [
{
"name": {
"$t": "YouTube"
},
"uri": {
"$t": "http://www.youtube.com/"
}
}
],
"generator": {
"$t": "YouTube data API",
"version": "2.1",
"uri": "http://gdata.youtube.com"
},
"openSearch$totalResults": {
"$t": 10595
},
"openSearch$startIndex": {
"$t": 1
},
"openSearch$itemsPerPage": {
"$t": 1
},
"entry": [
{
"id": {
"$t": "http://gdata.youtube.com/feeds/api/videos/HAUdFeouzgM"
},
"published": {
"$t": "2013-01-13T15:43:26.000Z"
},
"updated": {
"$t": "2013-01-13T15:43:26.000Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://gdata.youtube.com/schemas/2007#video"
},
{
"scheme": "http://gdata.youtube.com/schemas/2007/categories.cat",
"term": "Film",
"label": "Cine y animaciĆ³n"
}
],
"title": {
"$t": "Chica Troll en dibujo: TiparracoSA (IrukoArt)",
"type": "text"
},
"content": {
"$t": "Canal del artista creador: www.youtube.com Si quieres ver camaras ocultas dale aqui: www.youtube.com Si quieres ver a la chica troll VS pervertidos aqui: www.youtube.com Canal principal --- (Bromas con camara oculta y humor) www.youtube.com Sigueme en Twitter: twitter.com Sigueme en Facebook: www.facebook.com",
"type": "text"
},
"link": [
{
"rel": "alternate",
"type": "text/html",
"href": "http://www.youtube.com/watch?v=HAUdFeouzgM&feature=youtube_gdata"
},
{
"rel": "http://gdata.youtube.com/schemas/2007#video.responses",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos/HAUdFeouzgM/responses"
},
{
"rel": "http://gdata.youtube.com/schemas/2007#video.related",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos/HAUdFeouzgM/related"
},
{
"rel": "http://gdata.youtube.com/schemas/2007#mobile",
"type": "text/html",
"href": "http://m.youtube.com/details?v=HAUdFeouzgM"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/api/videos/HAUdFeouzgM"
}
],
"author": [
{
"name": {
"$t": "TiparracoTV"
},
"uri": {
"$t": "http://gdata.youtube.com/feeds/api/users/TiparracoTV"
}
}
],
"gd$comments": {
"gd$feedLink": {
"rel": "http://gdata.youtube.com/schemas/2007#comments",
"href": "http://gdata.youtube.com/feeds/api/videos/HAUdFeouzgM/comments",
"countHint": 0
}
},
"media$group": {
"media$category": [
{
"$t": "Film",
"label": "Cine y animaciĆ³n",
"scheme": "http://gdata.youtube.com/schemas/2007/categories.cat"
}
],
"media$content": [
{
"url": "http://www.youtube.com/v/HAUdFeouzgM?version=3&f=videos&app=youtube_gdata",
"type": "application/x-shockwave-flash",
"medium": "video",
"isDefault": "true",
"expression": "full",
"duration": 324,
"yt$format": 5
},
{
"url": "rtsp://v1.cache2.c.youtube.com/CiILENy73wIaGQkDzi7qFR0FHBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"type": "video/3gpp",
"medium": "video",
"expression": "full",
"duration": 324,
"yt$format": 1
},
{
"url": "rtsp://v1.cache2.c.youtube.com/CiILENy73wIaGQkDzi7qFR0FHBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"type": "video/3gpp",
"medium": "video",
"expression": "full",
"duration": 324,
"yt$format": 6
}
],
"media$description": {
"$t": "Canal del artista creador: www.youtube.com Si quieres ver camaras ocultas dale aqui: www.youtube.com Si quieres ver a la chica troll VS pervertidos aqui: www.youtube.com Canal principal --- (Bromas con camara oculta y humor) www.youtube.com Sigueme en Twitter: twitter.com Sigueme en Facebook: www.facebook.com",
"type": "plain"
},
"media$keywords": {
},
"media$player": [
{
"url": "http://www.youtube.com/watch?v=HAUdFeouzgM&feature=youtube_gdata_player"
}
],
"media$thumbnail": [
{
"url": "http://i.ytimg.com/vi/HAUdFeouzgM/0.jpg",
"height": 360,
"width": 480,
"time": "00:02:42"
},
{
"url": "http://i.ytimg.com/vi/HAUdFeouzgM/1.jpg",
"height": 90,
"width": 120,
"time": "00:01:21"
},
{
"url": "http://i.ytimg.com/vi/HAUdFeouzgM/2.jpg",
"height": 90,
"width": 120,
"time": "00:02:42"
},
{
"url": "http://i.ytimg.com/vi/HAUdFeouzgM/3.jpg",
"height": 90,
"width": 120,
"time": "00:04:03"
}
],
"media$title": {
"$t": "Chica Troll en dibujo: TiparracoSA (IrukoArt)",
"type": "plain"
},
"yt$duration": {
"seconds": "324"
}
},
"yt$statistics": {
"favoriteCount": "0",
"viewCount": "1"
}
}
]
}
}
I want to access some elements like title, tags, and link to use in my script. I eval json and i try to access to elements, but are inside arrays and another json objects i think and can't get the script work:
var datos=data.responseText;
var respuesta = eval("(" + data.responseText + ")");
alert(respuesta.entry.title);
This code don't work, how i can access to the elements?
Try alert(respuesta.entry[0].title); instead. entry is an array.
EDIT Also as we noted in the comments entry is yet one more level deeper in the json. The correct expression is actually: alert(respuesta.feed.entry[0].title);. I suggest you use Online JSON Beautifier to beutify your json and make it easier to understand.

Categories