Skip to content
jsonforge.app
Back to blog
Tutorial15 min read

JSON Examples in 7 Languages (With Code)

JSON is universal, but every language handles it differently. This is a side-by-side reference for parsing, serializing, and handling errors in seven popular languages.

JavaScript

JavaScript is JSON's native home. Parse with JSON.parse, serialize with JSON.stringify, and always wrap parsing in try/catch.

typescript
// Parse a JSON string into an object (always guard with try/catch)
let data;
try {
  data = JSON.parse('{"name": "Alice", "age": 30}');
  console.log(data.name); // "Alice"
} catch (err) {
  console.error("Invalid JSON:", err.message);
}

// Serialize an object back to JSON
const json = JSON.stringify(data, null, 2);

// Fetch JSON from an API (res.json() rejects on invalid JSON)
const res = await fetch("/api/users/1");
const user = await res.json(); // parsed automatically

Python

Python's built-in json module maps JSON objects to dicts and arrays to lists. Use json.loads (string → object) and json.dumps (object → string).

python
import json

# Parse JSON string into a dict
data = json.loads('{"name": "Alice", "age": 30}')

# Serialize a dict to a pretty JSON string
text = json.dumps(data, indent=2, ensure_ascii=False)

# Read/write a JSON file
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

Go

Go's encoding/json package maps JSON to structs via tags. Use json.Marshal to serialize and json.Unmarshal to parse, with struct tags controlling field names.

go
type User struct {
    Name string   `json:"name"`
    Age  int      `json:"age"`
}

// Struct → JSON
b, _ := json.Marshal(User{Name: "Alice", Age: 30})

// JSON → struct
var u User
_ = json.Unmarshal([]byte(`{"name":"Bob","age":25}`), &u)

Rust

Rust uses the serde and serde_json crates for zero-cost, type-safe (de)serialization. Derive Serialize/Deserialize on a struct, and serde_json handles the rest — including precise error messages with line and column when parsing fails.

rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct User {
    name: String,
    age: u8,
}

fn main() -> Result<(), serde_json::Error> {
    // JSON → struct
    let u: User = serde_json::from_str(r#"{"name":"Alice","age":30}"#)?;

    // Struct → JSON (pretty-printed)
    let json = serde_json::to_string_pretty(&u)?;
    println!("{}", json);
    Ok(())
}

PHP

PHP has native json_encode/json_decode with no dependency. Pass true as the second argument to json_decode to get associative arrays instead of stdClass objects, and always check json_last_error() — json_decode returns null on failure, which is also a valid JSON value.

php
<?php
// PHP array → JSON
$json = json_encode(["name" => "Alice", "age" => 30],
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// JSON → PHP array
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON error: " . json_last_error_msg();
}

Java

Java typically uses Jackson's ObjectMapper. Records (Java 16+) make clean DTOs with no boilerplate — Jackson binds to them directly, including unknown-property handling via configure.

java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;

record User(String name, int age) {}

ObjectMapper mapper = new ObjectMapper()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

// JSON → record
User user = mapper.readValue("{"name":"Alice","age":30}", User.class);

// Record → JSON
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);

C#

Modern C# uses System.Text.Json (built into .NET). Attributes like JsonPropertyName map JSON naming conventions to PascalCase properties, and JsonSerializerOptions control casing on the way out.

csharp
using System.Text.Json;
using System.Text.Json.Serialization;

public class User
{
    [JsonPropertyName("name")]
    public string Name { get; set; } = "";

    [JsonPropertyName("age")]
    public int Age { get; set; }
}

// JSON → object
var user = JsonSerializer.Deserialize<User>(
    "{\"name\":\"Alice\",\"age\":30}")!;

// Object → JSON (camelCase to match JSON conventions)
var options = new JsonSerializerOptions {
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
string json = JsonSerializer.Serialize(user, options);

Universal best practices

Always handle parse errors — malformed JSON will crash unguarded code. For production APIs, validate against a JSON Schema before processing. Prefer typed structs/classes over generic maps in compiled languages. Pretty-print during development, minify in production.

FAQ

Which language has the fastest JSON parser?
Compiled languages (Go, Rust, Java with Jackson, C# with System.Text.Json) generally outperform interpreted ones. For most apps the difference is negligible compared to network and database costs.
Should I use a typed struct or a generic map?
Typed structs/classes catch schema mismatches at compile time and give you autocomplete. Use generic maps only when the shape is truly dynamic or unknown.

Try these tools

Related articles