// Parse a JSON string into an object
const raw = '{"name":"Alice","age":30,"active":true}';
const user = JSON.parse(raw);
console.log(user.name); // "Alice"
// Convert an object to a formatted JSON string
const data = {
id: 1,
tags: ["dev", "api"],
address: { city: "NYC", zip: "10001" },
score: null,
};
const pretty = JSON.stringify(data, null, 2);
// Custom replacer — omit sensitive fields
const safe = JSON.stringify(data, (key, val) =>
key === "id" ? undefined : val
);
// Reviver — transform values during parsing
const parsed = JSON.parse('{"date":"2025-01-15T00:00:00Z"}', (key, val) =>
key === "date" ? new Date(val) : val
);
// Fetch JSON from an API
const res = await fetch("https://api.example.com/users/1");
const json = await res.json();
// Parse a JSON string into an object
const raw = '{"name":"Alice","age":30,"active":true}';
const user = JSON.parse(raw);
console.log(user.name); // "Alice"
// Convert an object to a formatted JSON string
const data = {
id: 1,
tags: ["dev", "api"],
address: { city: "NYC", zip: "10001" },
score: null,
};
const pretty = JSON.stringify(data, null, 2);
// Custom replacer — omit sensitive fields
const safe = JSON.stringify(data, (key, val) =>
key === "id" ? undefined : val
);
// Reviver — transform values during parsing
const parsed = JSON.parse('{"date":"2025-01-15T00:00:00Z"}', (key, val) =>
key === "date" ? new Date(val) : val
);
// Fetch JSON from an API
const res = await fetch("https://api.example.com/users/1");
const json = await res.json();
import json
from pathlib import Path
# Parse a JSON string
raw = '{"name": "Alice", "age": 30, "active": true}'
user = json.loads(raw)
print(user["name"]) # Alice
# Serialize to a formatted JSON string
data = {
"id": 1,
"tags": ["dev", "api"],
"address": {"city": "NYC", "zip": "10001"},
"score": None, # becomes null in JSON
}
pretty = json.dumps(data, indent=2, ensure_ascii=False)
# Read JSON from a file
config = json.loads(Path("config.json").read_text())
# Write JSON to a file
Path("output.json").write_text(
json.dumps(data, indent=2)
)
# Custom encoder for non-serializable types
from datetime import datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json.dumps({"now": datetime.now()}, cls=DateEncoder)
import json
from pathlib import Path
# Parse a JSON string
raw = '{"name": "Alice", "age": 30, "active": true}'
user = json.loads(raw)
print(user["name"]) # Alice
# Serialize to a formatted JSON string
data = {
"id": 1,
"tags": ["dev", "api"],
"address": {"city": "NYC", "zip": "10001"},
"score": None, # becomes null in JSON
}
pretty = json.dumps(data, indent=2, ensure_ascii=False)
# Read JSON from a file
config = json.loads(Path("config.json").read_text())
# Write JSON to a file
Path("output.json").write_text(
json.dumps(data, indent=2)
)
# Custom encoder for non-serializable types
from datetime import datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json.dumps({"now": datetime.now()}, cls=DateEncoder)
// Define a typed interface for JSON data
interface User {
name: string;
age: number;
active: boolean;
tags: string[];
address: { city: string; zip: string };
}
// Type-safe parsing with validation
function parseUser(raw: string): User {
const data: unknown = JSON.parse(raw);
if (
typeof data === "object" && data !== null &&
"name" in data && "age" in data
) {
return data as User;
}
throw new Error("Invalid user JSON");
}
// Generic fetch helper with typed response
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<T>;
}
const user = await fetchJson<User>("/api/user/1");
// Partial updates with Pick / Omit
type UserUpdate = Partial<Pick<User, "name" | "age">>;
const patch: UserUpdate = { name: "Bob" };
await fetch("/api/user/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
// Define a typed interface for JSON data
interface User {
name: string;
age: number;
active: boolean;
tags: string[];
address: { city: string; zip: string };
}
// Type-safe parsing with validation
function parseUser(raw: string): User {
const data: unknown = JSON.parse(raw);
if (
typeof data === "object" && data !== null &&
"name" in data && "age" in data
) {
return data as User;
}
throw new Error("Invalid user JSON");
}
// Generic fetch helper with typed response
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<T>;
}
const user = await fetchJson<User>("/api/user/1");
// Partial updates with Pick / Omit
type UserUpdate = Partial<Pick<User, "name" | "age">>;
const patch: UserUpdate = { name: "Bob" };
await fetch("/api/user/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class JsonExample {
// Define a POJO for JSON mapping
record User(String name, int age, boolean active, List<String> tags) {}
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Deserialize JSON string to object
String raw = """
{"name":"Alice","age":30,"active":true,"tags":["dev","api"]}
""";
User user = gson.fromJson(raw, User.class);
System.out.println(user.name()); // Alice
// Serialize object to JSON
String json = gson.toJson(user);
// Parse into a generic Map
Map<String, Object> map = gson.fromJson(raw,
new TypeToken<Map<String, Object>>(){}.getType());
// Parse a JSON array
String arr = """
[{"name":"Alice"},{"name":"Bob"}]
""";
List<User> users = gson.fromJson(arr,
new TypeToken<List<User>>(){}.getType());
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class JsonExample {
// Define a POJO for JSON mapping
record User(String name, int age, boolean active, List<String> tags) {}
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Deserialize JSON string to object
String raw = """
{"name":"Alice","age":30,"active":true,"tags":["dev","api"]}
""";
User user = gson.fromJson(raw, User.class);
System.out.println(user.name()); // Alice
// Serialize object to JSON
String json = gson.toJson(user);
// Parse into a generic Map
Map<String, Object> map = gson.fromJson(raw,
new TypeToken<Map<String, Object>>(){}.getType());
// Parse a JSON array
String arr = """
[{"name":"Alice"},{"name":"Bob"}]
""";
List<User> users = gson.fromJson(arr,
new TypeToken<List<User>>(){}.getType());
}
}
package main
import (
"encoding/json"
"fmt"
"os"
)
// Struct tags control JSON field names
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Active bool `json:"active"`
Tags []string `json:"tags,omitempty"`
Address *Address `json:"address,omitempty"`
}
type Address struct {
City string `json:"city"`
Zip string `json:"zip"`
}
func main() {
// Unmarshal JSON into a struct
raw := `{"name":"Alice","age":30,"active":true}`
var user User
json.Unmarshal([]byte(raw), &user)
fmt.Println(user.Name) // Alice
// Marshal struct to indented JSON
out, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(out))
// Decode from a stream (file, HTTP body, etc.)
file, _ := os.Open("data.json")
defer file.Close()
var data User
json.NewDecoder(file).Decode(&data)
// Dynamic parsing with map
var generic map[string]interface{}
json.Unmarshal([]byte(raw), &generic)
}
package main
import (
"encoding/json"
"fmt"
"os"
)
// Struct tags control JSON field names
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Active bool `json:"active"`
Tags []string `json:"tags,omitempty"`
Address *Address `json:"address,omitempty"`
}
type Address struct {
City string `json:"city"`
Zip string `json:"zip"`
}
func main() {
// Unmarshal JSON into a struct
raw := `{"name":"Alice","age":30,"active":true}`
var user User
json.Unmarshal([]byte(raw), &user)
fmt.Println(user.Name) // Alice
// Marshal struct to indented JSON
out, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(out))
// Decode from a stream (file, HTTP body, etc.)
file, _ := os.Open("data.json")
defer file.Close()
var data User
json.NewDecoder(file).Decode(&data)
// Dynamic parsing with map
var generic map[string]interface{}
json.Unmarshal([]byte(raw), &generic)
}
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
// Derive macros for automatic JSON serialization
#[derive(Debug, Serialize, Deserialize)]
struct User {
name: String,
age: u32,
active: bool,
#[serde(default)]
tags: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<Address>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Address {
city: String,
zip: String,
}
fn main() -> serde_json::Result<()> {
// Deserialize from a JSON string
let raw = r#"{"name":"Alice","age":30,"active":true}"#;
let user: User = serde_json::from_str(raw)?;
println!("{}", user.name); // Alice
// Serialize to a pretty JSON string
let json = serde_json::to_string_pretty(&user)?;
// Build JSON dynamically with the json! macro
let val = json!({
"status": "ok",
"count": 42,
"items": ["a", "b", "c"]
});
// Parse into an untyped Value for dynamic access
let v: Value = serde_json::from_str(raw)?;
println!("{}", v["name"]); // "Alice"
Ok(())
}
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
// Derive macros for automatic JSON serialization
#[derive(Debug, Serialize, Deserialize)]
struct User {
name: String,
age: u32,
active: bool,
#[serde(default)]
tags: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<Address>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Address {
city: String,
zip: String,
}
fn main() -> serde_json::Result<()> {
// Deserialize from a JSON string
let raw = r#"{"name":"Alice","age":30,"active":true}"#;
let user: User = serde_json::from_str(raw)?;
println!("{}", user.name); // Alice
// Serialize to a pretty JSON string
let json = serde_json::to_string_pretty(&user)?;
// Build JSON dynamically with the json! macro
let val = json!({
"status": "ok",
"count": 42,
"items": ["a", "b", "c"]
});
// Parse into an untyped Value for dynamic access
let v: Value = serde_json::from_str(raw)?;
println!("{}", v["name"]); // "Alice"
Ok(())
}
<?php
// Decode a JSON string into an associative array
$raw = '{"name":"Alice","age":30,"active":true}';
$user = json_decode($raw, associative: true);
echo $user['name']; // Alice
// Decode into an object (stdClass)
$obj = json_decode($raw);
echo $obj->name; // Alice
// Encode an array to a formatted JSON string
$data = [
'id' => 1,
'tags' => ['dev', 'api'],
'address' => ['city' => 'NYC', 'zip' => '10001'],
'score' => null,
];
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// Error handling for malformed JSON
$bad = json_decode('invalid json');
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'Parse error: ' . json_last_error_msg();
}
// Read and write JSON files
$config = json_decode(file_get_contents('config.json'), true);
file_put_contents('output.json', json_encode($data, JSON_PRETTY_PRINT));
<?php
// Decode a JSON string into an associative array
$raw = '{"name":"Alice","age":30,"active":true}';
$user = json_decode($raw, associative: true);
echo $user['name']; // Alice
// Decode into an object (stdClass)
$obj = json_decode($raw);
echo $obj->name; // Alice
// Encode an array to a formatted JSON string
$data = [
'id' => 1,
'tags' => ['dev', 'api'],
'address' => ['city' => 'NYC', 'zip' => '10001'],
'score' => null,
];
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// Error handling for malformed JSON
$bad = json_decode('invalid json');
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'Parse error: ' . json_last_error_msg();
}
// Read and write JSON files
$config = json_decode(file_get_contents('config.json'), true);
file_put_contents('output.json', json_encode($data, JSON_PRETTY_PRINT));
require 'json'
# Parse a JSON string into a Hash
raw = '{"name":"Alice","age":30,"active":true}'
user = JSON.parse(raw)
puts user['name'] # Alice
# Parse with symbolized keys
user = JSON.parse(raw, symbolize_names: true)
puts user[:name] # Alice
# Generate formatted JSON from a Hash
data = {
id: 1,
tags: %w[dev api],
address: { city: 'NYC', zip: '10001' },
score: nil # becomes null in JSON
}
puts JSON.pretty_generate(data)
# Read JSON from a file
config = JSON.parse(File.read('config.json'))
# Write JSON to a file
File.write('output.json', JSON.pretty_generate(data))
# Custom serialization with #to_json
class User
attr_accessor :name, :age
def to_json(*args)
{ name: @name, age: @age }.to_json(*args)
end
end
require 'json'
# Parse a JSON string into a Hash
raw = '{"name":"Alice","age":30,"active":true}'
user = JSON.parse(raw)
puts user['name'] # Alice
# Parse with symbolized keys
user = JSON.parse(raw, symbolize_names: true)
puts user[:name] # Alice
# Generate formatted JSON from a Hash
data = {
id: 1,
tags: %w[dev api],
address: { city: 'NYC', zip: '10001' },
score: nil # becomes null in JSON
}
puts JSON.pretty_generate(data)
# Read JSON from a file
config = JSON.parse(File.read('config.json'))
# Write JSON to a file
File.write('output.json', JSON.pretty_generate(data))
# Custom serialization with #to_json
class User
attr_accessor :name, :age
def to_json(*args)
{ name: @name, age: @age }.to_json(*args)
end
end
using System.Text.Json;
using System.Text.Json.Serialization;
// Define a record for JSON mapping
public record User(
string Name,
int Age,
bool Active,
string[] Tags
);
// Deserialize JSON into a typed object
var raw = """{"name":"Alice","age":30,"active":true,"tags":["dev"]}""";
var opts = new JsonSerializerOptions {
PropertyNameCaseInsensitive = true
};
var user = JsonSerializer.Deserialize<User>(raw, opts)!;
Console.WriteLine(user.Name); // Alice
// Serialize to indented JSON
var json = JsonSerializer.Serialize(user, new JsonSerializerOptions {
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
// Parse dynamic JSON with JsonDocument
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
var name = root.GetProperty("name").GetString();
// Work with JsonNode for mutable access
var node = JsonNode.Parse(raw)!;
node["age"] = 31;
Console.WriteLine(node.ToJsonString());
using System.Text.Json;
using System.Text.Json.Serialization;
// Define a record for JSON mapping
public record User(
string Name,
int Age,
bool Active,
string[] Tags
);
// Deserialize JSON into a typed object
var raw = """{"name":"Alice","age":30,"active":true,"tags":["dev"]}""";
var opts = new JsonSerializerOptions {
PropertyNameCaseInsensitive = true
};
var user = JsonSerializer.Deserialize<User>(raw, opts)!;
Console.WriteLine(user.Name); // Alice
// Serialize to indented JSON
var json = JsonSerializer.Serialize(user, new JsonSerializerOptions {
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
// Parse dynamic JSON with JsonDocument
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
var name = root.GetProperty("name").GetString();
// Work with JsonNode for mutable access
var node = JsonNode.Parse(raw)!;
node["age"] = 31;
Console.WriteLine(node.ToJsonString());
import Foundation
// Define a Codable struct for JSON mapping
struct User: Codable {
let name: String
let age: Int
let active: Bool
let tags: [String]?
}
// Decode JSON data into a struct
let raw = #"{"name":"Alice","age":30,"active":true}"#
let data = raw.data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
print(user.name) // Alice
// Encode struct to formatted JSON
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let json = try encoder.encode(user)
print(String(data: json, encoding: .utf8)!)
// Custom key mapping with CodingKeys
struct ApiResponse: Codable {
let userId: Int
let createdAt: String
enum CodingKeys: String, CodingKey {
case userId = "user_id"
case createdAt = "created_at"
}
}
// Dynamic parsing with JSONSerialization
let obj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let name = obj["name"] as? String
import Foundation
// Define a Codable struct for JSON mapping
struct User: Codable {
let name: String
let age: Int
let active: Bool
let tags: [String]?
}
// Decode JSON data into a struct
let raw = #"{"name":"Alice","age":30,"active":true}"#
let data = raw.data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
print(user.name) // Alice
// Encode struct to formatted JSON
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let json = try encoder.encode(user)
print(String(data: json, encoding: .utf8)!)
// Custom key mapping with CodingKeys
struct ApiResponse: Codable {
let userId: Int
let createdAt: String
enum CodingKeys: String, CodingKey {
case userId = "user_id"
case createdAt = "created_at"
}
}
// Dynamic parsing with JSONSerialization
let obj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let name = obj["name"] as? String
import kotlinx.serialization.*
import kotlinx.serialization.json.*
// Data class with serialization annotations
@Serializable
data class User(
val name: String,
val age: Int,
val active: Boolean,
val tags: List<String> = emptyList()
)
fun main() {
val json = Json { prettyPrint = true; ignoreUnknownKeys = true }
// Deserialize JSON string to object
val raw = """{"name":"Alice","age":30,"active":true}"""
val user = json.decodeFromString<User>(raw)
println(user.name) // Alice
// Serialize object to JSON
val output = json.encodeToString(user)
// Dynamic parsing with JsonElement
val element = json.parseToJsonElement(raw)
val name = element.jsonObject["name"]?.jsonPrimitive?.content
// Build JSON dynamically
val built = buildJsonObject {
put("status", "ok")
put("count", 42)
putJsonArray("items") {
add("a"); add("b"); add("c")
}
}
println(json.encodeToString(built))
}
import kotlinx.serialization.*
import kotlinx.serialization.json.*
// Data class with serialization annotations
@Serializable
data class User(
val name: String,
val age: Int,
val active: Boolean,
val tags: List<String> = emptyList()
)
fun main() {
val json = Json { prettyPrint = true; ignoreUnknownKeys = true }
// Deserialize JSON string to object
val raw = """{"name":"Alice","age":30,"active":true}"""
val user = json.decodeFromString<User>(raw)
println(user.name) // Alice
// Serialize object to JSON
val output = json.encodeToString(user)
// Dynamic parsing with JsonElement
val element = json.parseToJsonElement(raw)
val name = element.jsonObject["name"]?.jsonPrimitive?.content
// Build JSON dynamically
val built = buildJsonObject {
put("status", "ok")
put("count", 42)
putJsonArray("items") {
add("a"); add("b"); add("c")
}
}
println(json.encodeToString(built))
}