Working with JSON in Python, Java & PHP

Complete guide to parsing, creating, and manipulating JSON data across popular languages

Last updated: January 21, 2026 • 12 min read

JSON is the universal data format. Learn how to work with it in three of the most popular programming languages.

🐍 Working with JSON in Python

Python's built-in json module makes working with JSON simple and intuitive.

Parsing JSON in Python

import json

# Parse JSON string to Python dict
json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)

print(data["name"])  # Output: John
print(type(data))    # Output: <class 'dict'>

Creating JSON in Python

import json

# Python dict to JSON string
user = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "hobbies": ["reading", "coding", "gaming"]
}

json_string = json.dumps(user)
print(json_string)

# Pretty print with indentation
pretty_json = json.dumps(user, indent=2)
print(pretty_json)

Reading JSON from File (Python)

import json

# Read JSON file
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

# Write JSON file
user = {"name": "John", "age": 30}
with open('output.json', 'w') as file:
    json.dump(user, file, indent=2)

Handling Errors in Python

import json

try:
    data = json.loads('{"name": "John", "age": }')  # Invalid JSON
except json.JSONDecodeError as e:
    print(f"JSON Error: {e.msg}")
    print(f"At line {e.lineno}, column {e.colno}")

Python JSON Data Type Mapping

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
true/falseTrue/False
nullNone

☕ Working with JSON in Java

Java doesn't have built-in JSON support, but libraries like Gson, Jackson, and org.json make it easy.

Using Gson Library

First, add Gson to your project (Maven):

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Parsing JSON in Java (Gson)

import com.google.gson.Gson;

// Define a User class
class User {
    String name;
    int age;
    String city;
}

public class JsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        
        // Parse JSON string
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        User user = gson.fromJson(json, User.class);
        
        System.out.println(user.name);  // Output: John
        System.out.println(user.age);   // Output: 30
    }
}

Creating JSON in Java (Gson)

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class User {
    String name;
    int age;
    String city;
    
    User(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
}

public class JsonExample {
    public static void main(String[] args) {
        User user = new User("John", 30, "New York");
        
        // Convert to JSON
        Gson gson = new Gson();
        String json = gson.toJson(user);
        System.out.println(json);
        
        // Pretty print
        Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
        String prettyJson = prettyGson.toJson(user);
        System.out.println(prettyJson);
    }
}

Reading JSON from File (Java)

import com.google.gson.Gson;
import java.io.*;

public class JsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        
        // Read from file
        try (Reader reader = new FileReader("data.json")) {
            User user = gson.fromJson(reader, User.class);
            System.out.println(user.name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // Write to file
        User user = new User("John", 30, "New York");
        try (Writer writer = new FileWriter("output.json")) {
            gson.toJson(user, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using Jackson Library

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // Parse JSON
        String json = "{\"name\":\"John\",\"age\":30}";
        User user = mapper.readValue(json, User.class);
        
        // Create JSON
        String output = mapper.writeValueAsString(user);
        
        // Pretty print
        String pretty = mapper.writerWithDefaultPrettyPrinter()
                              .writeValueAsString(user);
    }
}

🐘 Working with JSON in PHP

PHP has built-in functions json_encode() and json_decode() for JSON handling.

Parsing JSON in PHP

<?php
// Parse JSON string to associative array
$json = '{"name":"John","age":30,"city":"New York"}';
$data = json_decode($json, true);  // true for associative array

echo $data['name'];  // Output: John
echo $data['age'];   // Output: 30

// Parse to object (default)
$obj = json_decode($json);
echo $obj->name;     // Output: John
echo $obj->age;      // Output: 30
?>

Creating JSON in PHP

<?php
// Array to JSON
$user = [
    "name" => "John",
    "age" => 30,
    "city" => "New York",
    "hobbies" => ["reading", "coding"]
];

$json = json_encode($user);
echo $json;

// Pretty print
$pretty = json_encode($user, JSON_PRETTY_PRINT);
echo $pretty;

// Preserve Unicode characters
$unicode = json_encode($user, JSON_UNESCAPED_UNICODE);
?>

Reading JSON from File (PHP)

<?php
// Read JSON file
$json = file_get_contents('data.json');
$data = json_decode($json, true);
print_r($data);

// Write JSON file
$user = ["name" => "John", "age" => 30];
$json = json_encode($user, JSON_PRETTY_PRINT);
file_put_contents('output.json', $json);
?>

Handling Errors in PHP

<?php
$json = '{"name": "John", "age": }';  // Invalid JSON
$data = json_decode($json);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
    // Output: JSON Error: Syntax error
}
?>

Common PHP JSON Options

<?php
$data = ["name" => "John", "age" => 30];

// Pretty print
$json = json_encode($data, JSON_PRETTY_PRINT);

// Don't escape unicode
$json = json_encode($data, JSON_UNESCAPED_UNICODE);

// Don't escape slashes
$json = json_encode($data, JSON_UNESCAPED_SLASHES);

// Force object instead of array
$json = json_encode($data, JSON_FORCE_OBJECT);

// Combine options
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
?>

Quick Comparison

TaskPythonJava (Gson)PHP
Parse JSONjson.loads()gson.fromJson()json_decode()
Create JSONjson.dumps()gson.toJson()json_encode()
Read Filejson.load(file)gson.fromJson(reader)json_decode(file_get_contents())
Write Filejson.dump(data, file)gson.toJson(obj, writer)file_put_contents(json_encode())
Pretty Printindent=2setPrettyPrinting()JSON_PRETTY_PRINT

Best Practices (All Languages)

  1. Always Validate: Use try-catch/error handling when parsing JSON from external sources
  2. Use Strong Typing: Define classes/models for your JSON data structure
  3. Handle Null Values: Check for null/None/nil before accessing nested properties
  4. Pretty Print for Development: Use indentation during development for readability
  5. Minify for Production: Remove whitespace for production to reduce size
  6. Sanitize Input: Never trust JSON from external sources without validation

Tools for Working with JSON

🔍 JSON Validator

Validate JSON before using in your code

Validate JSON →

✨ JSON Formatter

Format and beautify your JSON

Format JSON →

Conclusion

Working with JSON is essential in modern programming. Whether you're using Python's simple built-in module, Java's powerful libraries, or PHP's straightforward functions, the concepts remain the same: parse JSON strings into native data structures and serialize your objects back to JSON.

Test Your JSON

Before using JSON in your code, validate it first!

Validate JSON Free →