Practical examples of parsing JSON data in programming languages

If you work with APIs, you live in JSON. And the fastest way to get better is to study real examples of parsing JSON data in programming languages you actually use. In this guide, we’ll walk through hands-on examples of parsing JSON data in programming languages like JavaScript, Python, Java, C#, Go, and Ruby, and see how they differ in syntax, safety, and performance. Instead of vague theory, we’ll focus on real examples pulled from everyday API tasks: calling a REST endpoint, handling nested JSON from a payment provider, working with streaming JSON from a log service, and validating untrusted input. Along the way, you’ll see which features matter in 2024–2025: native JSON support, typed models, async parsing, and streaming for large payloads. If you’ve ever copied sample code from Stack Overflow and hoped for the best, this guide will give you cleaner, more deliberate patterns you can reuse across projects.
Written by
Jamie
Published

Real-world examples of parsing JSON data in programming languages

Let’s start where developers actually live: turning API responses into usable data structures. Below are concrete examples of parsing JSON data in programming languages you’re likely to encounter on a modern backend or frontend team.

We’ll keep the same simple JSON payload across languages so you can compare:

{
  "id": 123,
  "name": "Alice",
  "email": "alice@example.com",
  "roles": ["admin", "editor"],
  "profile": {
    "country": "US",
    "newsletter": true
  }
}

This is close to the kind of user object you’d see from an authentication or user profile API.


JavaScript and TypeScript: the most familiar example of JSON parsing

If you want the simplest example of parsing JSON data in programming languages, JavaScript wins. JSON is literally “JavaScript Object Notation,” so the syntax maps almost directly.

JavaScript: parse JSON from an API

async function fetchUser(userId) {
  const response = await fetch(`/api/users/${userId}`);
  if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
  }

  const data = await response.json(); // parse JSON

  console.log(data.name);           // "Alice"
  console.log(data.roles[0]);       // "admin"
  console.log(data.profile.country); // "US"

  return data;
}

This is one of the best examples of parsing JSON data in programming languages for beginners because:

  • response.json() handles the parsing step.
  • You work with plain objects and arrays.
  • It matches how browser and Node.js APIs behave in 2024.

TypeScript: safer parsing with types

Modern teams increasingly prefer TypeScript so they can catch shape mismatches early.

interface UserProfile {
  country: string;
  newsletter: boolean;
}

interface User {
  id: number;
  name: string;
  email: string;
  roles: string[];
  profile: UserProfile;
}

async function fetchUser(userId: number): Promise<User> {
  const response = await fetch(`/api/users/${userId}`);
  const data = (await response.json()) as User;

  // TypeScript will now type-check these
  data.roles.forEach(role => console.log(role.toUpperCase()));

  return data;
}

This example of parsing JSON data in programming languages shows how TypeScript gives you static checking without changing the runtime behavior.


Python: examples of parsing JSON data with json and pydantic

Python’s json module is part of the standard library, so you get JSON parsing out of the box.

Basic Python parsing with json.loads

import json

payload = '{"id": 123, "name": "Alice", "roles": ["admin", "editor"]}'

user = json.loads(payload)

print(user["name"])      # Alice
print(user["roles"][0])  # admin

For many scripts, this is enough. But for production APIs, teams in 2024–2025 often use data validation libraries.

Python with pydantic for validated models

pydantic (used heavily in FastAPI) adds typed models and validation.

from pydantic import BaseModel, EmailStr
from typing import List

class UserProfile(BaseModel):
  country: str
  newsletter: bool

class User(BaseModel):
  id: int
  name: str
  email: EmailStr
  roles: List[str]
  profile: UserProfile

json_str = '''{
  "id": 123,
  "name": "Alice",
  "email": "alice@example.com",
  "roles": ["admin", "editor"],
  "profile": {"country": "US", "newsletter": true}
}'''

user = User.model_validate_json(json_str)

print(user.email)          # validated email
print(user.profile.country)

This is one of the best examples of parsing JSON data in programming languages when you care about correctness. Invalid email formats or missing fields raise errors early, instead of silently failing later.

For more on JSON syntax and data types, the official JSON specification at IETF (RFC 8259) is still the reference standard.


Java: examples include Jackson and Gson for JSON parsing

In the Java world, JSON parsing is handled by libraries. The two big names are Jackson and Gson.

Java with Jackson: mapping JSON to POJOs

import com.fasterxml.jackson.databind.ObjectMapper;

public class UserProfile {
    public String country;
    public boolean newsletter;
}

public class User {
    public int id;
    public String name;
    public String email;
    public String[] roles;
    public UserProfile profile;
}

ObjectMapper mapper = new ObjectMapper();

String json = "{" +
  "\"id\": 123," +
  "\"name\": \"Alice\"," +
  "\"email\": \"alice@example.com\"," +
  "\"roles\": [\"admin\", \"editor\"]," +
  "\"profile\": {\"country\": \"US\", \"newsletter\": true}" +
"}";

User user = mapper.readValue(json, User.class);
System.out.println(user.name);
System.out.println(user.profile.country);

This example of parsing JSON data in programming languages highlights a Java strength: once you define the class, the mapper does the heavy lifting.

Java streaming parsing for large JSON

In 2024, large JSON payloads from analytics or observability platforms are common. Jackson’s streaming API helps you parse them without loading everything into memory.

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

JsonFactory factory = new JsonFactory();
try (JsonParser parser = factory.createParser(largeInputStream)) {
    while (!parser.isClosed()) {
        JsonToken token = parser.nextToken();
        if (JsonToken.FIELD_NAME.equals(token) && "id".equals(parser.getCurrentName())) {
            parser.nextToken();
            int id = parser.getIntValue();
            // process id
        }
    }
}

If you’re processing gigabytes of JSON logs, this is one of the more realistic examples of parsing JSON data in programming languages at scale.


C#: examples of parsing JSON with System.Text.Json

.NET developers used to reach for Newtonsoft.Json by default. Since .NET Core 3.0, System.Text.Json has become the standard choice.

C# parsing into dynamic objects

using System.Text.Json;

var json = @"{
  \"id\": 123,
  \"name\": \"Alice\",
  \"email\": \"alice@example.com\",
  \"roles\": [\"admin\", \"editor\"],
  \"profile\": {""country"": ""US"", ""newsletter"": true}
}";

using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;

string name = root.GetProperty("name").GetString();
string country = root.GetProperty("profile").GetProperty("country").GetString();

C# parsing into typed records

public record UserProfile(string Country, bool Newsletter);

public record User(int Id, string Name, string Email, string[] Roles, UserProfile Profile);

var user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user.Name);
Console.WriteLine(user.Profile.Country);

With records and System.Text.Json, the .NET ecosystem now has one of the cleaner examples of parsing JSON data in programming languages with strong typing.

For guidance on security when handling untrusted data (including JSON), Microsoft’s secure coding guidance and the OWASP JSON security cheat sheets are worth reading; OWASP’s materials are accessible at owasp.org.


Go: idiomatic examples of parsing JSON into structs

Go’s standard library has first-class JSON support via encoding/json. The pattern is consistent and easy to scan in code reviews.

package main

import (
    "encoding/json"
    "fmt"
)

type UserProfile struct {
    Country    string `json:"country"`
    Newsletter bool   `json:"newsletter"`
}

type User struct {
    ID      int         `json:"id"`
    Name    string      `json:"name"`
    Email   string      `json:"email"`
    Roles   []string    `json:"roles"`
    Profile UserProfile `json:"profile"`
}

func main() {
    jsonStr := `{
        "id": 123,
        "name": "Alice",
        "email": "alice@example.com",
        "roles": ["admin", "editor"],
        "profile": {"country": "US", "newsletter": true}
    }`

    var user User
    if err := json.Unmarshal([]byte(jsonStr), &user); err != nil {
        panic(err)
    }

    fmt.Println(user.Name)
    fmt.Println(user.Profile.Country)
}

Go’s struct tags make this one of the clearest examples of parsing JSON data in programming languages when you want a direct mapping from JSON keys to typed fields.


Ruby: quick examples of parsing JSON for scripts and Rails apps

Ruby’s json library is also part of the standard distribution.

require 'json'

json_str = '{"id":123,"name":"Alice","roles":["admin","editor"]}'

user = JSON.parse(json_str)

puts user["name"]      # Alice
puts user["roles"][0]  # admin

In Rails, controllers typically parse JSON automatically from request bodies, but you still work with the Hash-like structure that JSON.parse returns.


Comparing these examples of parsing JSON data in programming languages

Now that you’ve seen several real examples, a few patterns stand out:

  • Native vs library-based parsing
    JavaScript, Python, Go, Ruby, and C# all provide native or standard-library JSON parsing. Java leans heavily on external libraries like Jackson and Gson.

  • Dynamic vs static typing
    JavaScript and plain Python give you dynamic flexibility but fewer guarantees. TypeScript, Java, C#, Go, and Python with pydantic provide structure and validation.

  • Streaming vs in-memory parsing
    Java’s Jackson streaming API and similar tools in other languages address modern realities: logs, telemetry, and analytics data can be massive. In those cases, the best examples of parsing JSON data in programming languages rely on streaming to avoid memory blowups.

  • Validation and security
    When parsing JSON from external APIs, you’re effectively handling untrusted input. Typed models and validators (TypeScript, pydantic, C# records, Go structs) help reduce common bugs. For security guidance on input validation and data handling, the U.S. Cybersecurity & Infrastructure Security Agency (CISA) publishes secure coding resources at cisa.gov.

These differences matter if you’re designing cross-language APIs or migrating services from XML to JSON.


When JSON beats XML (and when it doesn’t)

Since this sits in a JSON vs XML context, it’s worth grounding the discussion.

Where JSON shines in 2024–2025:

  • Web APIs, especially RESTful and GraphQL backends
  • Mobile apps (iOS, Android, cross-platform frameworks)
  • Event streams and logging pipelines
  • Configuration files for tools and cloud services

Most modern API providers, from fintech platforms to public-health dashboards, publish JSON endpoints first. Even government and academic datasets increasingly ship JSON alongside or instead of XML. For example, many U.S. open data portals, such as data.gov, provide JSON output for civic datasets.

Where XML still appears:

  • Legacy enterprise integrations
  • Some SOAP-based services
  • Niche domains that rely on XML schemas and signatures

But if you’re starting a new API today, your developers will expect JSON. That’s why seeing many concrete examples of parsing JSON data in programming languages is more valuable than reviewing XML parsing patterns.


FAQ: examples of parsing JSON data in programming languages

Q1. What are some common examples of parsing JSON data in programming languages?
Common examples include:

  • A JavaScript frontend calling a REST API and using response.json() to render user data.
  • A Python backend using json.loads or pydantic to parse incoming webhook payloads.
  • A Java microservice mapping JSON to POJOs with Jackson.
  • A Go service decoding JSON into structs from a message queue.
  • A C# ASP.NET Core API using System.Text.Json to read request bodies into typed models.

Q2. Can you show an example of parsing nested JSON safely?
Yes. In Python with pydantic, nested models handle this cleanly:

class Profile(BaseModel):
  country: str
  newsletter: bool

class User(BaseModel):
  id: int
  profile: Profile

user = User.model_validate_json(json_str)
print(user.profile.country)

This pattern appears across languages: nested structs in Go, nested records in C#, nested classes in Java.

Q3. How do I handle invalid JSON when parsing?
Every example of parsing JSON data in programming languages should include error handling. For instance, in JavaScript:

try {
  const data = JSON.parse(maybeBrokenJson);
} catch (err) {
  console.error('Invalid JSON', err);
}

Python raises json.JSONDecodeError, Go’s json.Unmarshal returns an error, and other languages follow similar patterns.

Q4. Are there performance differences between languages when parsing JSON?
Yes, but in many API workloads, network latency dominates. Go and Rust are popular when JSON parsing speed truly matters, such as telemetry pipelines. Within language ecosystems, newer libraries often focus on speed; for example, System.Text.Json in .NET was introduced in part for performance reasons.

Q5. Where can I learn more about JSON standards and best practices?
For the formal standard, see RFC 8259 at the IETF. For secure coding guidance around data parsing and input validation, OWASP’s documentation at owasp.org and security resources from cisa.gov are helpful starting points.

Explore More Data Formats: JSON vs XML in APIs

Discover more examples and insights in this category.

View All Data Formats: JSON vs XML in APIs