Skip to content
gemini-json-parsing logo

Gemini JSON Parsing

gemini-json-parsing

Parse Gemini CLI headless output (JSON and stream-JSON formats). Covers response extraction, stats interpretation, error handling, and tool call analysis. Use when processing Gemini CLI programmatic output.

SKILL.md

Full skill instructions

Gemini JSON Parsing

🚨 MANDATORY: Invoke gemini-cli-docs First

STOP - Before providing ANY response about Gemini JSON output:

  1. INVOKE gemini-cli-docs skill
  2. QUERY for the specific output format topic
  3. BASE all responses EXCLUSIVELY on official documentation loaded

Overview

Skill for parsing Gemini CLI's structured output formats. Essential for integration workflows where Claude needs to process Gemini's responses programmatically.

When to Use This Skill

Keywords: parse gemini output, json output, stream json, gemini stats, token usage, jq parsing, gemini response

Use this skill when:

  • Extracting responses from Gemini JSON output
  • Analyzing token usage and costs
  • Parsing tool call statistics
  • Handling errors from Gemini CLI
  • Building automation pipelines

Output Formats

Standard JSON (--output-format json)

Single JSON object returned after completion:

{
  "response": "The main AI-generated content",
  "stats": {
    "models": {
      "gemini-2.5-pro": {
        "api": {
          "totalRequests": 2,
          "totalErrors": 0,
          "totalLatencyMs": 5053
        },
        "tokens": {
          "prompt": 24939,
          "candidates": 20,
          "total": 25113,
          "cached": 21263,
          "thoughts": 154,
          "tool": 0
        }
      }
    },
    "tools": {
      "totalCalls": 1,
      "totalSuccess": 1,
      "totalFail": 0,
      "totalDurationMs": 1881,
      "totalDecisions": {
        "accept": 0,
        "reject": 0,
        "modify": 0,
        "auto_accept": 1
      },
      "byName": {
        "google_web_search": {
          "count": 1,
          "success": 1,
          "fail": 0,
          "durationMs": 1881
        }
      }
    },
    "files": {
      "totalLinesAdded": 0,
      "totalLinesRemoved": 0
    }
  },
  "error": {
    "type": "ApiError",
    "message": "Error description",
    "code": 500
  }
}

Stream JSON (--output-format stream-json)

Newline-delimited JSON (JSONL) with real-time events:

Event TypeDescriptionFields
initSession startsession_id, model, timestamp
messageUser/​assistant messagesrole, content, timestamp
tool_useTool call requeststool_name, tool_id, parameters
tool_resultTool execution resultstool_id, status, output
errorNon-fatal errorstype, message
resultFinal outcomestatus, stats

Example stream:

{"type":"init","timestamp":"2025-10-10T12:00:00.000Z","session_id":"abc123","model":"gemini-2.5-flash"}
{"type":"message","role":"user","content":"List files","timestamp":"2025-10-10T12:00:01.000Z"}
{"type":"tool_use","tool_name":"Bash","tool_id":"bash-123","parameters":{"command":"ls -la"}}
{"type":"tool_result","tool_id":"bash-123","status":"success","output":"file1.txt\nfile2.txt"}
{"type":"message","role":"assistant","content":"Here are the files...","delta":true}
{"type":"result","status":"success","stats":{"total_tokens":250}}

Common Extraction Patterns

Extract Response Text

# Get main response
gemini "query" --output-format json | jq -r '.response'

# With error handling
result=$(gemini "query" --output-format json)
if echo "$result" | jq -e '.error' > /​dev/​null 2>&1; then
  echo "Error: $(echo "$result" | jq -r '.error.message')"
else
  echo "$result" | jq -r '.response'
fi

Token Statistics

# Total tokens used
echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.total) | add'

# Cached tokens (cost savings)
echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.cached) | add'

# Billable tokens
total=$(echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.total) | add')
cached=$(echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.cached) | add')
echo "Billable: $((total - cached))"

# Tokens by model
echo "$result" | jq '.stats.models | to_entries[] | "\(.key): \(.value.tokens.total) tokens"'

Tool Call Analysis

# Total tool calls
echo "$result" | jq '.stats.tools.totalCalls'

# List tools used
echo "$result" | jq -r '.stats.tools.byName | keys | join(", ")'

# Tool success rate
total=$(echo "$result" | jq '.stats.tools.totalCalls')
success=$(echo "$result" | jq '.stats.tools.totalSuccess')
echo "Success rate: $((success * 100 / total))%"

# Detailed tool stats
echo "$result" | jq '.stats.tools.byName | to_entries[] | "\(.key): \(.value.count) calls, \(.value.durationMs)ms"'

Model Usage

# List models used
echo "$result" | jq -r '.stats.models | keys | join(", ")'

# Model latency
echo "$result" | jq '.stats.models | to_entries[] | "\(.key): \(.value.api.totalLatencyMs)ms"'

# Request counts
echo "$result" | jq '.stats.models | to_entries[] | "\(.key): \(.value.api.totalRequests) requests"'

Error Handling

# Check for errors
if echo "$result" | jq -e '.error' > /​dev/​null 2>&1; then
  error_type=$(echo "$result" | jq -r '.error.type // "Unknown"')
  error_msg=$(echo "$result" | jq -r '.error.message // "No message"')
  error_code=$(echo "$result" | jq -r '.error.code // "N/​A"')
  echo "Error [$error_type]: $error_msg (code: $error_code)"
  exit 1
fi

File Modifications

# Lines changed
echo "$result" | jq '"Added: \(.stats.files.totalLinesAdded), Removed: \(.stats.files.totalLinesRemoved)"'

Stream Processing

Filter by Event Type

# Get only tool results
gemini --output-format stream-json -p "query" | jq -r 'select(.type == "tool_result")'

# Get only errors
gemini --output-format stream-json -p "query" | jq -r 'select(.type == "error")'

# Get assistant messages
gemini --output-format stream-json -p "query" | jq -r 'select(.type == "message" and .role == "assistant") | .content'

Real-time Monitoring

# Watch tool calls as they happen
gemini --output-format stream-json -p "analyze code" | while read line; do
  type=$(echo "$line" | jq -r '.type')
  case "$type" in
    tool_use)
      tool=$(echo "$line" | jq -r '.tool_name')
      echo "[TOOL] Calling: $tool"
      ;;
    tool_result)
      status=$(echo "$line" | jq -r '.status')
      echo "[RESULT] Status: $status"
      ;;
    error)
      msg=$(echo "$line" | jq -r '.message')
      echo "[ERROR] $msg"
      ;;
  esac
done

Quick Reference

Whatjq Command
Response text.response
Total tokens.stats.models | to_entries | map(.value.tokens.total) | add
Cached tokens.stats.models | to_entries | map(.value.tokens.cached) | add
Tool calls.stats.tools.totalCalls
Tools used.stats.tools.byName | keys | join(", ")
Models used.stats.models | keys | join(", ")
Error message.error.message // "none"
Error type.error.type // "none"
Lines added.stats.files.totalLinesAdded
Lines removed.stats.files.totalLinesRemoved
Total latency.stats.models | to_entries | map(.value.api.totalLatencyMs) | add

Complete Example

#!/​bin/​bash
# Analyze code and report stats

result=$(cat src/​main.ts | gemini "Review this code for security issues" --output-format json)

# Check for errors
if echo "$result" | jq -e '.error' > /​dev/​null 2>&1; then
  echo "Error: $(echo "$result" | jq -r '.error.message')"
  exit 1
fi

# Extract response
echo "=== Security Review ==="
echo "$result" | jq -r '.response'

# Report stats
echo ""
echo "=== Stats ==="
total=$(echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.total) | add // 0')
cached=$(echo "$result" | jq '.stats.models | to_entries | map(.value.tokens.cached) | add // 0')
models=$(echo "$result" | jq -r '.stats.models | keys | join(", ") | if . == "" then "none" else . end')
tools=$(echo "$result" | jq '.stats.tools.totalCalls // 0')

echo "Tokens: $total (cached: $cached)"
echo "Models: $models"
echo "Tool calls: $tools"

Test Scenarios

Scenario 1: Extract Response

Query: "How do I extract the response from Gemini JSON output?" Expected Behavior:

  • Skill activates on "parse gemini output" or "json output"
  • Provides jq extraction pattern Success Criteria: User receives .response extraction command

Scenario 2: Token Usage Analysis

Query: "How do I track token usage from Gemini CLI?" Expected Behavior:

  • Skill activates on "token usage" or "gemini stats"
  • Provides stats extraction patterns Success Criteria: User receives token calculation jq commands

Scenario 3: Stream Processing

Query: "How do I process Gemini CLI stream-json output?" Expected Behavior:

  • Skill activates on "stream json"
  • Provides JSONL processing patterns Success Criteria: User receives real-time stream processing example

References

Query gemini-cli-docs for official documentation on:

  • "json output format"
  • "stream-json output"
  • "headless mode"

Version History

  • v1.1.0 (2025-12-01): Added Test Scenarios section
  • v1.0.0 (2025-11-25): Initial release

More Productivity & Planning skills

brainstorming logo
Productivity & Planning

brainstorming

Structured design dialogue that validates ideas before implementation begins.

295.4K 385.7K
View
ui-ux-pro-max logo
Productivity & Planning

ui-ux-pro-max

Comprehensive design intelligence for web and mobile UI/UX across 10 technology stacks.

133.1K 383.9K
View
writing-plans logo
Productivity & Planning

writing-plans

Comprehensive implementation plans for multi-step tasks, breaking down specs into bite-sized, testable steps.

295.4K 268K
View
using-superpowers logo
Productivity & Planning

using-superpowers

Introduction to the obra skills system with mandatory skill invocation rules and best practices.

295.4K 259.8K
View
executing-plans logo
Productivity & Planning

executing-plans

Execute a written implementation plan with critical review and task checkpoints.

295.4K 229.1K
View
dispatching-parallel-agents logo
Productivity & Planning

dispatching-parallel-agents

Delegate independent tasks to specialized agents working concurrently with isolated context.

295.4K 206.3K
View
using-git-worktrees logo
Productivity & Planning

using-git-worktrees

Isolated git worktrees with smart directory selection and safety verification.

295.4K 205.2K
View
webapp-testing logo
Productivity & Planning

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

179.7K 170.6K
View
content-strategy logo
Productivity & Planning

content-strategy

Plan searchable and shareable content that drives traffic, builds authority, and generates leads.

53.3K 150.9K
View
repo-intake-and-plan logo
Productivity & Planning

repo-intake-and-plan

README-first repository scanner that extracts commands and classifies reproduction candidates without executing them.

497 139.6K
View
marketing-ideas logo
Productivity & Planning

marketing-ideas

Brainstorm and prioritize marketing strategies tailored to your SaaS stage, budget, and goals.

53.3K 137.2K
View
site-architecture logo
Productivity & Planning

site-architecture

Plan and optimize your website's page hierarchy, navigation, URL structure, and internal linking.

53.3K 112.8K
View

Productivity AI tools

Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View
SaveDay logo
Productivity

SaveDay

Capture, organize, and utilize your knowledge effortlessly.

Free
View
Any Summary logo
Productivity

Any Summary

Instant Summaries of Audio & Video Interviews with AnySummary

Freemium
View
M
Productivity

Map This

Transform PDFs into engaging mind maps.

Freemium
View
ChatPDF logo
Productivity

ChatPDF

Chat with any PDF instantly

Free
View
I
Productivity

intellisay

Create an optimal daily plan using your voice

Paid
View
A
Productivity

Aurora AI

A productivity platform to centralize organizational knowledge and workflows with contextual AI assistance.

Paid
View
AskYourPDF logo
Productivity

AskYourPDF

AskYourPDF Pricing Plans: Tailored to Your Needs

Free
View