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

JSON Examples in 7 Languages: JavaScript, Python, Go, Rust, PHP, Java, C#

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.

// Parse a JSON string into an object
const data = JSON.parse('{"name": "Alice", "age": 30}');
console.log(data.name); // "Alice"

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

// Fetch JSON from an API
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).

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.

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, PHP, Java, C#

Rust uses the serde and serde_json crates for zero-cost, type-safe (de)serialization. PHP has native json_encode/json_decode with no dependency. Java typically uses Jackson's ObjectMapper. Modern C# uses System.Text.Json.

<?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();
}

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.

Related articles