0
{
  videos: [
    {
      id: 'jbnddQ9l0IA',
      original_title: 'Undefined - Episode 1',
      title: 'Episode 1',
      artist: 'Undefined',
      duration: 1060,
      publishedAt: 2016-02-20T10:11:25.280Z
    },
    {
      id: 'SQzjzStU1RQ',
      original_title: 'Why dividing by zero is undefined | Functions and their graphs | Algebra II | Khan Academy',
      title: 'Why dividing by zero is undefined | Functions and their graphs | Algebra II | Khan Academy',
      artist: '',
      duration: 248,
      publishedAt: 2013-05-18T10:12:56.581Z
    }
  ],
  didyoumean: '',
  token: 'Abc',
  apikey: 'Abc'
}

How can I get the first item's "id" in the "videos" array as string? (I'm using Node.js)

I need this output:

jbnddQ9l0IA

Thanks...

  • JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Aug 28 '21 at 10:24
  • You can use a for loop to go through all the videos in the array. Then for each item you can use `.id` to find the id. – Kokodoko Aug 28 '21 at 10:25
  • @Kokodoko - OP said they just want the first one. – T.J. Crowder Aug 28 '21 at 10:26
  • Presumably you have the object shown referenced by a variable of some kind; let's call it `data`. If you want the first video's `id`, you'd use `data.videos[0].id`. You might check first if there are any videos, since otherwise that will throw an error. See the linked question's answers for details. – T.J. Crowder Aug 28 '21 at 10:27
  • That isn't valid JSON in the first place. – Quentin Aug 28 '21 at 10:29
  • @Quentin - Or even valid JavaScript, because of the unquoted bit after `publishedAt`. – T.J. Crowder Aug 28 '21 at 10:30

1 Answers1

1

Just treat the JSON object as an Object. <JSON-variable>.videos[0].id

Mohi
  • 94
  • 4
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help]. This is an **often repeated duplicate**, it doesn't need any answers posted to it. When you have a rep > 50 (you didn't when I started this comment) you can post a comment after voting to close the question as a duplicate, if no one else has, to try to help the OP understand how the linked question's answers apply. (I already have.) – T.J. Crowder Aug 28 '21 at 10:26