JSON in Multiple Programming Languages
A comprehensive guide to working with JSON across different programming languages with practical code examples.
One of JSON's greatest strengths is its universal support across programming languages. While the syntax remains the same, each language has its own libraries and methods for working with JSON data. This guide provides practical examples for the most popular languages.
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"hobbies": ["reading", "gaming", "hiking"],
"address": {
"city": "New York",
"country": "USA"
}
}
JavaScript / Node.js
JavaScript has native JSON support with built-in JSON object. No external libraries needed.
Parse JSON String to Object
const jsonString = '{"name": "John Doe", "age": 30}';
// Parse JSON string to object
const user = JSON.parse(jsonString);
console.log(user.name); // "John Doe"
console.log(user.age); // 30
Convert Object to JSON String
const user = {
name: "John Doe",
age: 30,
hobbies: ["reading", "gaming"]
};
// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"John Doe","age":30,"hobbies":["reading","gaming"]}'
// Pretty print with 2-space indentation
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
Fetch JSON from API
// Using fetch (browser & Node 18+)
const response = await fetch('https://api.example.com/users/1');
const user = await response.json();
console.log(user.name);
// Using axios
const axios = require('axios');
const { data } = await axios.get('https://api.example.com/users/1');
console.log(data.name);
Read/Write JSON File (Node.js)
const fs = require('fs');
// Read JSON file
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
// Write JSON file
fs.writeFileSync('output.json', JSON.stringify(data, null, 2));
Python
Python includes the json module in its standard library.
Parse JSON String to Dictionary
import json
json_string = '{"name": "John Doe", "age": 30}'
# Parse JSON string to dictionary
user = json.loads(json_string)
print(user["name"]) # John Doe
print(user["age"]) # 30
Convert Dictionary to JSON String
import json
user = {
"name": "John Doe",
"age": 30,
"hobbies": ["reading", "gaming"]
}
# Convert to JSON string
json_string = json.dumps(user)
print(json_string)
# Pretty print with indentation
pretty_json = json.dumps(user, indent=2)
print(pretty_json)
# Sort keys alphabetically
sorted_json = json.dumps(user, indent=2, sort_keys=True)
print(sorted_json)
Read/Write JSON File
import json
# Read JSON file
with open('data.json', 'r') as file:
data = json.load(file)
# Write JSON file
with open('output.json', 'w') as file:
json.dump(data, file, indent=2)
Fetch JSON from API
import requests
response = requests.get('https://api.example.com/users/1')
user = response.json()
print(user["name"])
Java
Java requires external libraries. Popular choices are Jackson, Gson, and org.json.
Using Jackson (Recommended)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Parse JSON string
String json = "{\"name\": \"John Doe\", \"age\": 30}";
JsonNode node = mapper.readTree(json);
System.out.println(node.get("name").asText()); // John Doe
System.out.println(node.get("age").asInt()); // 30
// Convert to POJO
User user = mapper.readValue(json, User.class);
System.out.println(user.getName());
}
}
// POJO class
class User {
private String name;
private int age;
// getters and setters
}
Using Gson
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class GsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
// Parse JSON string
String json = "{\"name\": \"John Doe\", \"age\": 30}";
JsonObject obj = gson.fromJson(json, JsonObject.class);
System.out.println(obj.get("name").getAsString());
// Convert to POJO
User user = gson.fromJson(json, User.class);
// Convert POJO to JSON
String jsonOutput = gson.toJson(user);
}
}
Read/Write JSON File
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
ObjectMapper mapper = new ObjectMapper();
// Read from file
User user = mapper.readValue(new File("data.json"), User.class);
// Write to file (pretty print)
mapper.writerWithDefaultPrettyPrinter()
.writeValue(new File("output.json"), user);
PHP
PHP has built-in JSON functions: json_encode() and json_decode().
Parse JSON String to Array/Object
<?php
$jsonString = '{"name": "John Doe", "age": 30}';
// Parse to object (default)
$user = json_decode($jsonString);
echo $user->name; // John Doe
echo $user->age; // 30
// Parse to associative array
$userArray = json_decode($jsonString, true);
echo $userArray["name"]; // John Doe
echo $userArray["age"]; // 30
Convert Array to JSON String
<?php
$user = [
"name" => "John Doe",
"age" => 30,
"hobbies" => ["reading", "gaming"]
];
// Convert to JSON string
$jsonString = json_encode($user);
echo $jsonString;
// Pretty print
$prettyJson = json_encode($user, JSON_PRETTY_PRINT);
echo $prettyJson;
// Handle Unicode properly
$jsonUnicode = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
Read/Write JSON File
<?php
// Read JSON file
$json = file_get_contents('data.json');
$data = json_decode($json, true);
// Write JSON file
file_put_contents('output.json', json_encode($data, JSON_PRETTY_PRINT));
Error Handling
<?php
$json = '{"invalid json}';
$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
// PHP 7.3+ with exceptions
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "JSON Error: " . $e->getMessage();
}
C# / .NET
.NET has built-in System.Text.Json (recommended for .NET Core 3+) and Newtonsoft.Json (popular third-party).
Using System.Text.Json (Built-in)
using System.Text.Json;
// Define a class
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public List<string> Hobbies { get; set; }
}
// Parse JSON string to object
string json = "{\"Name\": \"John Doe\", \"Age\": 30}";
User user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user.Name);
// Convert object to JSON string
string jsonOutput = JsonSerializer.Serialize(user);
// Pretty print
var options = new JsonSerializerOptions { WriteIndented = true };
string prettyJson = JsonSerializer.Serialize(user, options);
Using Newtonsoft.Json
using Newtonsoft.Json;
// Parse JSON string
string json = "{\"Name\": \"John Doe\", \"Age\": 30}";
User user = JsonConvert.DeserializeObject<User>(json);
// Convert to JSON string
string jsonOutput = JsonConvert.SerializeObject(user);
// Pretty print
string prettyJson = JsonConvert.SerializeObject(user, Formatting.Indented);
// Dynamic parsing (no class needed)
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.Name);
Read/Write JSON File
using System.Text.Json;
using System.IO;
// Read JSON file
string json = File.ReadAllText("data.json");
User user = JsonSerializer.Deserialize<User>(json);
// Write JSON file
var options = new JsonSerializerOptions { WriteIndented = true };
string output = JsonSerializer.Serialize(user, options);
File.WriteAllText("output.json", output);
Go (Golang)
Go has built-in JSON support in the encoding/json package.
Parse JSON to Struct
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
}
func main() {
jsonStr := `{"name": "John Doe", "age": 30, "hobbies": ["reading"]}`
var user User
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
panic(err)
}
fmt.Println(user.Name) // John Doe
fmt.Println(user.Age) // 30
}
Convert Struct to JSON
user := User{
Name: "John Doe",
Age: 30,
Hobbies: []string{"reading", "gaming"},
}
// Convert to JSON
jsonBytes, err := json.Marshal(user)
fmt.Println(string(jsonBytes))
// Pretty print
prettyBytes, err := json.MarshalIndent(user, "", " ")
fmt.Println(string(prettyBytes))
Read/Write JSON File
import (
"encoding/json"
"os"
)
// Read JSON file
file, _ := os.ReadFile("data.json")
var user User
json.Unmarshal(file, &user)
// Write JSON file
output, _ := json.MarshalIndent(user, "", " ")
os.WriteFile("output.json", output, 0644)
Ruby
Ruby includes the json library in its standard library.
Parse JSON String to Hash
require 'json'
json_string = '{"name": "John Doe", "age": 30}'
# Parse JSON string to hash
user = JSON.parse(json_string)
puts user["name"] # John Doe
puts user["age"] # 30
# Parse with symbol keys
user = JSON.parse(json_string, symbolize_names: true)
puts user[:name] # John Doe
Convert Hash to JSON String
require 'json'
user = {
name: "John Doe",
age: 30,
hobbies: ["reading", "gaming"]
}
# Convert to JSON string
json_string = user.to_json
puts json_string
# Or using JSON.generate
json_string = JSON.generate(user)
# Pretty print
pretty_json = JSON.pretty_generate(user)
puts pretty_json
Read/Write JSON File
require 'json'
# Read JSON file
data = JSON.parse(File.read('data.json'))
# Write JSON file
File.write('output.json', JSON.pretty_generate(data))
Rust
Rust uses the serde and serde_json crates for JSON handling.
Add to Cargo.toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Parse JSON to Struct
use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Serialize, Deserialize, Debug)]
struct User {
name: String,
age: u32,
hobbies: Vec<String>,
}
fn main() {
let json_str = r#"{"name": "John Doe", "age": 30, "hobbies": ["reading"]}"#;
// Parse JSON string to struct
let user: User = serde_json::from_str(json_str).unwrap();
println!("{}", user.name); // John Doe
println!("{}", user.age); // 30
}
Convert Struct to JSON
let user = User {
name: String::from("John Doe"),
age: 30,
hobbies: vec![String::from("reading")],
};
// Convert to JSON string
let json_string = serde_json::to_string(&user).unwrap();
println!("{}", json_string);
// Pretty print
let pretty_json = serde_json::to_string_pretty(&user).unwrap();
println!("{}", pretty_json);
Swift
Swift has built-in JSON support with Codable protocol and JSONDecoder/JSONEncoder.
Parse JSON to Struct
import Foundation
struct User: Codable {
let name: String
let age: Int
let hobbies: [String]
}
let jsonString = """
{"name": "John Doe", "age": 30, "hobbies": ["reading"]}
"""
// Parse JSON string to struct
let jsonData = jsonString.data(using: .utf8)!
let user = try JSONDecoder().decode(User.self, from: jsonData)
print(user.name) // John Doe
print(user.age) // 30
Convert Struct to JSON
let user = User(name: "John Doe", age: 30, hobbies: ["reading"])
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try encoder.encode(user)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
Kotlin
Kotlin commonly uses kotlinx.serialization or Java libraries like Jackson/Gson.
Using kotlinx.serialization
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class User(
val name: String,
val age: Int,
val hobbies: List<String>
)
fun main() {
val jsonString = """{"name": "John Doe", "age": 30, "hobbies": ["reading"]}"""
// Parse JSON string to data class
val user = Json.decodeFromString<User>(jsonString)
println(user.name) // John Doe
// Convert data class to JSON string
val json = Json.encodeToString(user)
println(json)
// Pretty print
val prettyJson = Json { prettyPrint = true }.encodeToString(user)
println(prettyJson)
}
Quick Reference Comparison
| Language | Parse Function | Stringify Function | Built-in? |
|---|---|---|---|
| JavaScript | JSON.parse() |
JSON.stringify() |
✅ Yes |
| Python | json.loads() |
json.dumps() |
✅ Yes |
| Java | mapper.readValue() |
mapper.writeValueAsString() |
❌ Jackson/Gson |
| PHP | json_decode() |
json_encode() |
✅ Yes |
| C# | JsonSerializer.Deserialize() |
JsonSerializer.Serialize() |
✅ Yes (.NET Core 3+) |
| Go | json.Unmarshal() |
json.Marshal() |
✅ Yes |
| Ruby | JSON.parse() |
.to_json |
✅ Yes |
| Rust | serde_json::from_str() |
serde_json::to_string() |
❌ serde_json |
| Swift | JSONDecoder().decode() |
JSONEncoder().encode() |
✅ Yes |
| Kotlin | Json.decodeFromString() |
Json.encodeToString() |
❌ kotlinx.serialization |
Generate Code from JSON
Use our JSON to Code Generator to automatically create type definitions and parsing code for your JSON: