> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/getsentry/cli/llms.txt
> Use this file to discover all available pages before exploring further.

# JSON Output for Scripting

> Use --json flag to parse CLI output in scripts and automation

Most Sentry CLI commands support the `--json` flag to output machine-readable JSON instead of human-formatted text. This makes it easy to integrate with scripts, CI/CD pipelines, and other automation tools.

## Using the --json Flag

Add `--json` to any supported command:

```bash theme={null}
sentry issue list --json
sentry project list --json
sentry org list --json
```

<Tabs>
  <Tab title="Human Output">
    ```bash theme={null}
    $ sentry org list
    SLUG          NAME                 REGION
    my-org        My Organization      US
    other-org     Other Org            EU
    ```
  </Tab>

  <Tab title="JSON Output">
    ```bash theme={null}
    $ sentry org list --json
    ```

    ```json theme={null}
    [
      {
        "id": "1081365",
        "slug": "my-org",
        "name": "My Organization",
        "dateCreated": "2024-01-15T10:30:00Z"
      },
      {
        "id": "2043821",
        "slug": "other-org",
        "name": "Other Org",
        "dateCreated": "2024-02-20T14:20:00Z"
      }
    ]
    ```
  </Tab>
</Tabs>

## Commands with JSON Support

### Organization Commands

```bash theme={null}
# List organizations
sentry org list --json

# View organization details
sentry org view my-org --json
```

<Accordion title="Example Output">
  ```json theme={null}
  {
    "id": "1081365",
    "slug": "my-org",
    "name": "My Organization",
    "dateCreated": "2024-01-15T10:30:00Z",
    "status": {
      "id": "active",
      "name": "Active"
    }
  }
  ```
</Accordion>

### Project Commands

```bash theme={null}
# List projects
sentry project list --json

# View project details
sentry project view my-project --json

# Create project
sentry project create my-app javascript-nextjs --json
```

<Accordion title="Example Output">
  ```json theme={null}
  {
    "id": "4505238472482816",
    "slug": "my-app",
    "name": "my-app",
    "platform": "javascript-nextjs",
    "dateCreated": "2024-03-05T16:45:00Z",
    "dsn": "https://abc123@o1234.ingest.us.sentry.io/4505238472482816"
  }
  ```
</Accordion>

### Issue Commands

```bash theme={null}
# List issues
sentry issue list --json

# View issue details
sentry issue view 123456789 --json

# AI analysis
sentry issue explain 123456789 --json
sentry issue plan 123456789 --cause 0 --json
```

<Accordion title="Example Output">
  ```json theme={null}
  [
    {
      "id": "123456789",
      "shortId": "MY-APP-G",
      "title": "TypeError: Cannot read property 'email' of null",
      "culprit": "authenticate_user",
      "level": "error",
      "status": "unresolved",
      "count": "42",
      "userCount": 15,
      "firstSeen": "2024-03-01T08:30:00Z",
      "lastSeen": "2024-03-05T14:20:00Z"
    }
  ]
  ```
</Accordion>

### Authentication Commands

```bash theme={null}
# Check auth status
sentry auth status --json

# Refresh token
sentry auth refresh --json
```

<Accordion title="Example Output">
  ```json theme={null}
  {
    "authenticated": true,
    "user": {
      "id": "123456",
      "email": "user@example.com",
      "name": "John Doe"
    },
    "source": "oauth"
  }
  ```
</Accordion>

## Parsing JSON Output

### Using jq

[jq](https://jqlang.github.io/jq/) is a powerful command-line JSON processor:

<CodeGroup>
  ```bash Extract specific fields theme={null}
  # Get organization slugs
  sentry org list --json | jq -r '.[].slug'

  # Get project platforms
  sentry project list --json | jq -r '.[].platform'

  # Count unresolved issues
  sentry issue list --json | jq '[.[] | select(.status == "unresolved")] | length'
  ```

  ```bash Filter and transform theme={null}
  # Find high-severity issues
  sentry issue list --json | jq '[.[] | select(.level == "error" or .level == "fatal")]'

  # Get issues with high user impact
  sentry issue list --json | jq '[.[] | select(.userCount > 10)] | sort_by(.userCount) | reverse'

  # Extract issue IDs and titles
  sentry issue list --json | jq -r '.[] | "\(.id): \(.title)"'
  ```

  ```bash Create reports theme={null}
  # CSV format
  echo "ID,Title,Count,Users" > issues.csv
  sentry issue list --json | jq -r '.[] | [.id, .title, .count, .userCount] | @csv' >> issues.csv

  # Markdown table
  echo "| ID | Title | Status |" > issues.md
  echo "|---|---|---|" >> issues.md
  sentry issue list --json | jq -r '.[] | "| \(.id) | \(.title) | \(.status) |"' >> issues.md
  ```
</CodeGroup>

### Using Python

```python theme={null}
import json
import subprocess

# Get issues
result = subprocess.run(
    ["sentry", "issue", "list", "--json"],
    capture_output=True,
    text=True,
    check=True
)
issues = json.loads(result.stdout)

# Filter high-priority issues
high_priority = [
    issue for issue in issues
    if issue['level'] in ['error', 'fatal'] and issue['userCount'] > 10
]

print(f"Found {len(high_priority)} high-priority issues")

# Create notifications
for issue in high_priority:
    print(f"⚠️  {issue['title']} - {issue['userCount']} users affected")
    print(f"   First seen: {issue['firstSeen']}")
    print(f"   Link: https://sentry.io/issues/{issue['id']}/")
```

### Using Node.js

```javascript theme={null}
const { execSync } = require('child_process');

// Get projects
const output = execSync('sentry project list --json', {
  encoding: 'utf-8'
});
const projects = JSON.parse(output);

// Group by platform
const byPlatform = projects.reduce((acc, project) => {
  const platform = project.platform || 'unknown';
  if (!acc[platform]) acc[platform] = [];
  acc[platform].push(project);
  return acc;
}, {});

// Print summary
for (const [platform, projs] of Object.entries(byPlatform)) {
  console.log(`${platform}: ${projs.length} projects`);
}
```

### Using Bash

```bash theme={null}
#!/bin/bash

# Get unresolved issues
ISSUES=$(sentry issue list --json)

# Count by level
ERRORS=$(echo "$ISSUES" | jq '[.[] | select(.level == "error")] | length')
WARNINGS=$(echo "$ISSUES" | jq '[.[] | select(.level == "warning")] | length')

echo "Errors: $ERRORS"
echo "Warnings: $WARNINGS"

# Alert if too many errors
if [ "$ERRORS" -gt 10 ]; then
  echo "⚠️  High error count detected!"
  # Send notification (Slack, email, etc.)
fi
```

## CI/CD Integration

### GitHub Actions

```yaml .github/workflows/monitor-issues.yml theme={null}
name: Monitor Sentry Issues

on:
  schedule:
    - cron: '0 */6 * * *'  # Every 6 hours
  workflow_dispatch:

jobs:
  check-issues:
    runs-on: ubuntu-latest
    steps:
      - name: Install Sentry CLI
        run: npm install -g @sentry/cli-next
      
      - name: Get high-priority issues
        env:
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
        run: |
          # Get issues from last 24 hours
          ISSUES=$(sentry issue list --period 24h --json)
          
          # Count critical issues
          CRITICAL=$(echo "$ISSUES" | jq '[.[] | select(.level == "fatal" or .level == "error")] | length')
          
          echo "critical_count=$CRITICAL" >> $GITHUB_OUTPUT
          echo "Found $CRITICAL critical issues"
        id: check
      
      - name: Create issue if threshold exceeded
        if: steps.check.outputs.critical_count > 10
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: 'High error count in Sentry',
              body: 'More than 10 critical issues detected in the last 24 hours.',
              labels: ['sentry', 'urgent']
            });
```

### GitLab CI

```yaml .gitlab-ci.yml theme={null}
sentry-check:
  stage: test
  image: node:20
  before_script:
    - npm install -g @sentry/cli-next
  script:
    - |
      # Get new issues
      ISSUES=$(sentry issue list --period 1h --json)
      COUNT=$(echo "$ISSUES" | jq 'length')
      
      echo "Found $COUNT new issues in the last hour"
      
      # Fail if too many issues
      if [ "$COUNT" -gt 5 ]; then
        echo "❌ Too many new issues detected!"
        exit 1
      fi
  only:
    - main
```

### Jenkins Pipeline

```groovy Jenkinsfile theme={null}
pipeline {
    agent any
    
    stages {
        stage('Check Sentry Issues') {
            steps {
                script {
                    // Get issue count
                    def issuesJson = sh(
                        script: 'sentry issue list --json',
                        returnStdout: true
                    ).trim()
                    
                    def issues = readJSON text: issuesJson
                    def unresolvedCount = issues.findAll { 
                        it.status == 'unresolved' 
                    }.size()
                    
                    echo "Unresolved issues: ${unresolvedCount}"
                    
                    if (unresolvedCount > 20) {
                        error "Too many unresolved issues: ${unresolvedCount}"
                    }
                }
            }
        }
    }
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Always validate JSON parsing">
    ```bash theme={null}
    # Check exit code before parsing
    if OUTPUT=$(sentry issue list --json 2>&1); then
      echo "$OUTPUT" | jq '.[] | .title'
    else
      echo "Command failed: $OUTPUT" >&2
      exit 1
    fi
    ```
  </Accordion>

  <Accordion title="Handle empty results">
    ```python theme={null}
    import json
    import subprocess

    result = subprocess.run(
        ["sentry", "issue", "list", "--json"],
        capture_output=True,
        text=True
    )

    if result.returncode == 0:
        issues = json.loads(result.stdout)
        if not issues:
            print("No issues found")
        else:
            # Process issues
            pass
    else:
        print(f"Error: {result.stderr}")
    ```
  </Accordion>

  <Accordion title="Use --limit to reduce output size">
    ```bash theme={null}
    # Get only the 10 most recent issues
    sentry issue list --limit 10 --json | jq '.'

    # Useful for CI/CD where you only need a sample
    sentry project list --limit 5 --json
    ```
  </Accordion>

  <Accordion title="Combine with other filters">
    ```bash theme={null}
    # Filter at CLI level, then at jq level
    sentry issue list --period 24h --status unresolved --json | \
      jq '[.[] | select(.userCount > 5)]'
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

### Invalid JSON Output

If you get invalid JSON, check if there are error messages mixed with the output:

```bash theme={null}
# Errors go to stderr, JSON to stdout
sentry issue list --json 2>/dev/null

# Or capture stderr separately
sentry issue list --json 2>errors.log
```

### Empty Output

Empty arrays are valid JSON:

```bash theme={null}
$ sentry issue list --json
[]
```

This means no issues match your filters. Check:

* Date range (`--period`)
* Status filter (`--status`)
* Project selection

### Encoding Issues

If you see encoding errors with special characters:

```python theme={null}
# Use UTF-8 encoding explicitly
result = subprocess.run(
    ["sentry", "issue", "list", "--json"],
    capture_output=True,
    text=True,
    encoding='utf-8'
)
```
