JSON snake_case to Go CamelCase Conversion

Understand how JSON snake_case keys like user_name are converted to Go CamelCase fields like UserName with proper json struct tags.

Struct Tags

Detailed Explanation

Converting snake_case JSON Keys to CamelCase Go Fields

JSON APIs commonly use snake_case naming (user_name, created_at), while Go conventions require CamelCase exported fields (UserName, CreatedAt). Struct tags bridge this gap.

Example JSON

{
  "user_id": 1001,
  "first_name": "Alice",
  "last_name": "Smith",
  "created_at": "2024-01-15T10:30:00Z",
  "is_active": true
}

Generated Go Struct

type User struct {
    UserID    int    `json:"user_id"`
    FirstName string `json:"first_name"`
    LastName  string `json:"last_name"`
    CreatedAt string `json:"created_at"`
    IsActive  bool   `json:"is_active"`
}

Conversion Rules

The converter applies these transformations:

  1. Split on underscoresuser_id splits into ["user", "id"].
  2. Capitalize each segmentuser becomes User, id becomes ID.
  3. Join segmentsUserID.
  4. Common initialisms — Go convention uppercases common abbreviations: ID, URL, HTTP, API, JSON, HTML, CSS, SQL.

So user_id becomes UserID (not UserId), and api_url becomes APIURL.

Why Tags Are Essential

Without the json:"user_id" tag, Go would look for a JSON key matching the field name exactly — "UserID" — and fail to match "user_id". The tag creates the mapping between the two naming conventions.

Bidirectional Conversion

When marshaling the struct back to JSON, the tags ensure the output uses the original snake_case keys, maintaining API compatibility:

data, _ := json.Marshal(user)
// {"user_id":1001,"first_name":"Alice",...}

This naming bridge is so fundamental that every JSON-to-Go converter handles it automatically.

Use Case

Python, Ruby, and many database ORMs use snake_case in their JSON output. When consuming these APIs from Go, the snake_case to CamelCase conversion with struct tags is required for proper unmarshaling.

Try It — JSON to Go Struct Converter

Open full tool