YouTube Transcripts

YouTube Transcript JSON: Get Timestamps Programmatically

··7 min read

Getting a YouTube transcript as structured JSON — with precise start and duration timestamps per segment — is a common need for search indexing, NLP pipelines, subtitle tooling, and chapter generation. This guide covers every practical path: youtube-transcript-api, yt-dlp's json3 format, and how to convert either into plain text or SRT.


What Does a YouTube Transcript Look Like as JSON?

Short answer: Each segment is a dict with three keys — text, start (seconds, float), and duration (seconds, float).

The canonical shape returned by youtube-transcript-api is a list of dicts:

[
  { "text": "welcome back to the channel", "start": 0.0,   "duration": 2.56 },
  { "text": "today we are building",       "start": 2.56,  "duration": 1.84 },
  { "text": "a full REST API from scratch", "start": 4.4,  "duration": 3.12 }
]

Each entry maps exactly to one caption cue. start is the cue's begin time in seconds from the video start. duration is how long the cue is displayed. There is no end key — compute it as start + duration if you need it.

This structure is consistent across auto-generated and manually uploaded captions, though auto-generated captions sometimes produce shorter, word-level cues rather than sentence-level ones.


Fetching the Transcript with youtube-transcript-api

Short answer: Three lines of Python — install the library, instantiate YouTubeTranscriptApi(), call .fetch(), then serialize with .to_raw_data().

Install the library:

pip install youtube-transcript-api

Fetch and serialize:

import json
from youtube_transcript_api import YouTubeTranscriptApi

video_id = "dQw4w9WgXcQ"  # replace with your target ID

ytt_api = YouTubeTranscriptApi()
fetched = ytt_api.fetch(video_id)
print(json.dumps(fetched.to_raw_data(), indent=2))

That prints a JSON array of segment dicts to stdout. To write it to a file:

with open(f"{video_id}.json", "w", encoding="utf-8") as f:
    json.dump(fetched.to_raw_data(), f, indent=2, ensure_ascii=False)

The ensure_ascii=False flag matters if the transcript contains non-ASCII characters (accented letters, CJK, etc.) — without it, Python will escape them as \uXXXX sequences.

Specifying a Language

Auto-detection picks the first available language. To request a specific one:

fetched = ytt_api.fetch(video_id, languages=["en"])

Pass a priority list to fall back gracefully:

fetched = ytt_api.fetch(video_id, languages=["en", "en-US", "en-GB"])

To list all available transcripts for a video (including auto-generated vs. manual, and which languages are translatable):

from youtube_transcript_api import YouTubeTranscriptApi

ytt_api = YouTubeTranscriptApi()
transcript_list = ytt_api.list(video_id)
for t in transcript_list:
    print(t.language, t.language_code, t.is_generated, t.is_translatable)

For a deeper walkthrough of language handling and error patterns, see our youtube-transcript-api Python guide.


Converting JSON Transcript to Plain Text

Short answer: Join the text fields with spaces, stripping any \n YouTube occasionally injects inside cues.

plain_text = " ".join(snippet.text.replace("\n", " ") for snippet in fetched)

For a paragraph-chunked version useful for LLM ingestion, group by a time window:

def chunk_by_seconds(fetched, window=60):
    chunks, current, t0 = [], [], fetched[0].start
    for snippet in fetched:
        current.append(snippet.text.replace("\n", " "))
        if snippet.start - t0 >= window:
            chunks.append(" ".join(current))
            current, t0 = [], snippet.start
    if current:
        chunks.append(" ".join(current))
    return chunks

paragraphs = chunk_by_seconds(fetched, window=60)

Each element in paragraphs is approximately 60 seconds of speech — a reasonable unit for embedding or display.


Converting JSON Transcript to SRT

Short answer: Format each segment as an SRT cue block using the start and start + duration times.

SRT expects a specific format:

1
00:00:00,000 --> 00:00:02,560
welcome back to the channel

2
00:00:02,560 --> 00:00:04,400
today we are building

Here is a minimal converter:

def seconds_to_srt_time(seconds: float) -> str:
    ms = int(round((seconds % 1) * 1000))
    s  = int(seconds)
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"

def transcript_to_srt(fetched) -> str:
    blocks = []
    for i, snippet in enumerate(fetched, start=1):
        start = seconds_to_srt_time(snippet.start)
        end   = seconds_to_srt_time(snippet.start + snippet.duration)
        text  = snippet.text.replace("\n", " ").strip()
        blocks.append(f"{i}\n{start} --> {end}\n{text}\n")
    return "\n".join(blocks)

srt_output = transcript_to_srt(fetched)
with open(f"{video_id}.srt", "w", encoding="utf-8") as f:
    f.write(srt_output)

The , separator before milliseconds (not .) is required by the SRT spec. Players that accept . are tolerant, but spec-compliant SRT uses commas.

For more on working with transcript timestamps, see our YouTube transcript timestamps guide.


The yt-dlp json3 Format

Short answer: yt-dlp --write-subs --sub-format json3 produces a different JSON schema — VTT cue objects rather than flat dicts — and requires more parsing work than youtube-transcript-api.

yt-dlp can download subtitles in several formats. The json3 format is YouTube's native subtitle blob:

yt-dlp \
  --skip-download \
  --write-subs \
  --write-auto-subs \
  --sub-langs en \
  --sub-format json3 \
  -o "%(id)s" \
  "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

This produces a file like dQw4w9WgXcQ.en.json3. The top-level structure is:

{
  "wireMagic": "pb3",
  "pens": [...],
  "wsWinStyles": [...],
  "wpWinPositions": [...],
  "events": [
    {
      "tStartMs": 0,
      "dDurMs": 2560,
      "segs": [{ "utf8": "welcome back to the channel" }]
    }
  ]
}

The useful fields live in events. Each event has:

  • tStartMs — start time in milliseconds (not seconds)
  • dDurMs — duration in milliseconds
  • segs — list of segment objects, each with a utf8 text field

To convert json3 to the same {text, start, duration} shape as youtube-transcript-api:

import json

with open("dQw4w9WgXcQ.en.json3") as f:
    raw = json.load(f)

segments = []
for event in raw.get("events", []):
    text = "".join(s.get("utf8", "") for s in event.get("segs", []))
    text = text.strip()
    if not text or text == "\n":
        continue
    segments.append({
        "text":     text,
        "start":    event["tStartMs"] / 1000.0,
        "duration": event.get("dDurMs", 0) / 1000.0,
    })

print(json.dumps(segments, indent=2, ensure_ascii=False))

One gotcha: json3 events often include empty segs entries or \n-only cues for styling — the if not text or text == "\n" guard drops those.

For a full comparison of yt-dlp subtitle formats and when to use each, see the yt-dlp YouTube subtitles guide.


Parsing Tips and Common Gotchas

Short answer: Watch for empty cues, overlapping timestamps in auto-generated tracks, and Unicode in json.dumps.

A few patterns that catch developers off guard:

Empty or whitespace-only cues. Auto-generated tracks include blank cues as spacers. Filter them before any downstream processing. Since FetchedTranscript is not a plain list, convert to raw data first if you need mutable filtering:

raw = fetched.to_raw_data()
clean = [s for s in raw if s["text"].strip()]

Overlapping timestamps. Adjacent cues sometimes share a start time or have a tiny gap. If you need non-overlapping windows (for audio alignment, for example), work on the raw data and clamp each cue's end to the next cue's start:

raw = fetched.to_raw_data()
for i in range(len(raw) - 1):
    max_end = raw[i + 1]["start"]
    raw[i]["duration"] = min(raw[i]["duration"], max_end - raw[i]["start"])

Rate limiting. youtube-transcript-api makes an HTTP request per get_transcript call. For batch processing dozens of videos, add a small delay between requests or run via a proxy to avoid 429s.

Private and age-gated videos. Neither library can fetch transcripts for private videos without authenticated cookies. yt-dlp supports --cookies-from-browser for age-gated content; youtube-transcript-api does not natively.

For a comprehensive look at error handling and fallback strategies, see the youtube-transcript-api guide.


When You Need Insight, Not Just JSON

Short answer: If your end goal is understanding a video — not wiring up a data pipeline — SkipTheWatch skips the JSON entirely and gives you a structured summary plus a chat interface.

Fetching and parsing transcript JSON is the right move when you are building something: a search index, a subtitle editor, a chapter generator, an NLP feature. The JSON is your raw material.

But sometimes the goal is simpler — you want to understand what a 90-minute video is actually about, ask it a question, or extract the one idea that matters — without writing or running any code. For that use case, SkipTheWatch processes the transcript server-side and returns a structured summary with key points, chapter breakdowns, and a chat interface where you can ask questions about the video directly.

No local setup, no library installs, no JSON parsing. $9/month after a 7-day free trial. Cancel anytime in the trial for $0. A card is required at sign-up.


Frequently Asked Questions

What is the JSON shape returned by youtube-transcript-api? A list of dicts, each with three keys: text (string), start (float, seconds from video start), and duration (float, seconds the cue is displayed). There is no end field — derive it as start + duration if needed.

How do I get a YouTube transcript as JSON with one command? Install youtube-transcript-api (pip install youtube-transcript-api), then run: python -c "import json; from youtube_transcript_api import YouTubeTranscriptApi; api = YouTubeTranscriptApi(); print(json.dumps(api.fetch('VIDEO_ID').to_raw_data(), indent=2))" — replacing VIDEO_ID with the 11-character video ID from the URL.

What is the difference between youtube-transcript-api JSON and yt-dlp json3? youtube-transcript-api returns a normalized Python list of {text, start, duration} dicts — ready to use directly. yt-dlp's json3 format is YouTube's raw subtitle blob with millisecond timestamps nested inside an events array. It requires extra parsing to reach the same shape. Use youtube-transcript-api for simplicity; use yt-dlp when you also need the video file or want to control authentication via browser cookies.

Can I get a transcript as JSON for auto-generated captions? Yes. youtube-transcript-api fetches auto-generated captions by default when no manual transcript exists. The JSON shape is identical. Auto-generated tracks tend to produce shorter, more fragmented cues than manually uploaded ones, so expect more entries in the list for the same video length.

Does youtube-transcript-api support all languages? It supports any language that YouTube has a caption track for. Use ytt_api.list(video_id) to see which language codes are available, then pass your preferred code to ytt_api.fetch(video_id, languages=["fr"]). Auto-generated tracks are available for a narrower set of languages than manual ones.

Skip the watch. Get the insight.

AI summaries of any YouTube video in seconds — key insights, timestamps, structured breakdowns. Start free — no credit card. Pro is $9/month for 500 summaries with a 7-day free trial, cancel anytime.

Get my free summaries

Free to start · No credit card · Upgrade anytime

Related Articles