How to Parse JSON in JavaScript, Python, Java, and PHP

Complete code examples for reading and writing JSON in JavaScript, Python, Java, and PHP — including real error handling.

How to Parse JSON in JavaScript, Python, Java, and PHP

Every language handles JSON a little differently — different function names, different error types, different edge cases that bite you in production. This guide covers the specifics for JavaScript, Python, Java, PHP, C#, and Ruby, with working code and the pitfalls worth knowing before you hit them.

JavaScript

Parsing JSON strings

JSON.parse() converts a JSON string into a JavaScript object. It throws a SyntaxError if the input is invalid:

const jsonString = '{"name":"Alice","age":30,"active":true}';

try {
  const obj = JSON.parse(jsonString);
  console.log(obj.name);  // "Alice"
  console.log(obj.age);   // 30
} catch (err) {
  console.error('Invalid JSON:', err.message);
}

Generating JSON strings

JSON.stringify() converts a JavaScript value to a JSON string. The second argument is a replacer (or null), and the third controls indentation:

const user = { name: 'Alice', age: 30, password: 'secret' };

// Exclude the password field
const safe = JSON.stringify(user, (key, val) => key === 'password' ? undefined : val, 2);
console.log(safe);
// {
//   "name": "Alice",
//   "age": 30
// }

Fetching JSON from an API

async function loadUser(id) {
  const res = await fetch(`https://api.example.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json(); // automatically calls JSON.parse
  return data;
}

JavaScript pitfall: large numbers lose precision

JavaScript numbers are 64-bit floats. Integers larger than Number.MAX_SAFE_INTEGER (253−1) lose precision silently. If your API returns 64-bit IDs like {"id": 9007199254740993}, parse them as strings or use BigInt:

// Safe: treat large IDs as strings in your schema
const data = JSON.parse('{"id":"9007199254740993"}');
const id = BigInt(data.id); // safe large integer

Reviver function for date reconstruction

const obj = JSON.parse('{"createdAt":"2025-05-10T09:00:00Z"}', (key, val) => {
  if (key === 'createdAt') return new Date(val);
  return val;
});
console.log(obj.createdAt instanceof Date); // true

Python

Parsing JSON strings and files

Python's standard library json module provides json.loads() for strings and json.load() for file objects:

import json

# From a string
text = '{"name": "Alice", "scores": [95, 87, 92]}'
data = json.loads(text)
print(data['name'])      # Alice
print(data['scores'][0]) # 95

# From a file
with open('data.json', 'r', encoding='utf-8') as f:
    config = json.load(f)
print(config['server']['port'])

Generating JSON

import json

user = {'name': 'Alice', 'age': 30, 'scores': [95, 87]}

# To string
print(json.dumps(user, indent=2))

# To file
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(user, f, indent=2, ensure_ascii=False)

Error handling

import json

try:
    data = json.loads('{"bad": json}')
except json.JSONDecodeError as e:
    print(f'Parse error at line {e.lineno}, col {e.colno}: {e.msg}')

Python pitfall: datetime objects are not serializable by default

from datetime import datetime
import json

now = datetime.utcnow()

# This raises TypeError: Object of type datetime is not JSON serializable
# json.dumps({'ts': now})

# Fix: use a custom encoder or isoformat()
print(json.dumps({'ts': now.isoformat() + 'Z'}))

Java

Java has no built-in JSON support. The two most widely used libraries are Jackson (the de facto standard) and Gson (popular in Android).

Jackson — parsing and generating

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

ObjectMapper mapper = new ObjectMapper();

// Parse JSON string into a typed object
String json = "{\"name\":\"Alice\",\"age\":30}";
User user = mapper.readValue(json, User.class);
System.out.println(user.getName()); // Alice

// Parse into a generic tree for unknown structures
JsonNode root = mapper.readTree(json);
System.out.println(root.get("age").asInt()); // 30

// Serialize object to JSON string
String output = mapper.writeValueAsString(user);

// Pretty print
String pretty = mapper.writerWithDefaultPrettyPrinter()
                      .writeValueAsString(user);

Jackson error handling

try {
    User u = mapper.readValue("{bad json}", User.class);
} catch (JsonProcessingException e) {
    System.err.println("JSON error: " + e.getMessage());
}

Gson — simpler for basic cases

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

Gson gson = new GsonBuilder().setPrettyPrinting().create();

// Deserialize
User user = gson.fromJson("{\"name\":\"Alice\"}", User.class);

// Serialize
String json = gson.toJson(user);

PHP

Parsing and generating JSON

PHP has json_decode() and json_encode() built into the language:

<?php
$jsonString = '{"name":"Alice","age":30,"active":true}';

// Decode to stdClass object (default)
$obj = json_decode($jsonString);
echo $obj->name; // Alice

// Decode to associative array (second arg = true)
$arr = json_decode($jsonString, true);
echo $arr['age']; // 30

// Encode back to JSON
$data = ['name' => 'Bob', 'scores' => [90, 85, 92]];
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Error handling in PHP

json_decode() returns null on failure — always check json_last_error():

<?php
$result = json_decode('{"bad": json}', true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('JSON parse error: ' . json_last_error_msg());
}

// PHP 7.3+: use the throw_on_error flag
try {
    $result = json_decode('{"bad": json}', true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    error_log('JSON error: ' . $e->getMessage());
}

PHP pitfall: large integers

By default PHP converts large JSON integers to floats, losing precision. Use JSON_BIGINT_AS_STRING to keep them as strings:

<?php
$data = json_decode('{"id":9007199254740993}', true, 512, JSON_BIGINT_AS_STRING);
echo $data['id']; // "9007199254740993" (string, precision preserved)

C# (.NET)

Since .NET 5, C# has a built-in System.Text.Json namespace. For older .NET or more flexible mapping, Newtonsoft.Json (Json.NET) is still widely used.

System.Text.Json — modern and built-in

using System.Text.Json;

// Parse JSON string into a typed object
string json = "{\"name\":\"Alice\",\"age\":30}";
var user = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(user.Name); // Alice

// Serialize to JSON string
var output = JsonSerializer.Serialize(user, new JsonSerializerOptions {
    WriteIndented = true
});

// Parse into a flexible document (no typed class needed)
using var doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
Console.WriteLine(root.GetProperty("age").GetInt32()); // 30

Error handling in C#

try {
    var data = JsonSerializer.Deserialize<User>("{bad json}");
} catch (JsonException ex) {
    Console.WriteLine($"JSON error at path {ex.Path}: {ex.Message}");
}

Newtonsoft.Json — more features, older projects

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// Deserialize to typed object
var user = JsonConvert.DeserializeObject<User>(json);

// Serialize
string output = JsonConvert.SerializeObject(user, Formatting.Indented);

// Dynamic access without a class
JObject obj = JObject.Parse(json);
string name = (string)obj["name"]; // Alice

Ruby

Ruby's standard library includes the json gem. JSON.parse returns a Hash; JSON.generate converts back to a string.

require 'json'

# Parse
json_string = '{"name":"Alice","age":30,"scores":[95,87,92]}'
data = JSON.parse(json_string)
puts data['name']       # Alice
puts data['scores'][0]  # 95

# Generate
hash = { name: 'Bob', age: 25 }
puts JSON.generate(hash)          # compact
puts JSON.pretty_generate(hash)   # indented

# Error handling
begin
  JSON.parse('{"bad": json}')
rescue JSON::ParserError => e
  puts "Parse error: #{e.message}"
end

# Read from file
config = JSON.parse(File.read('config.json'))
puts config['server']['port']

Common Cross-Language Patterns

Deep-cloning an object via JSON

A quick way to create a deep copy of a plain object (with no functions or circular references) is to serialize then deserialize:

// JavaScript
const original = { user: { name: 'Alice', scores: [95, 87] } };
const copy = JSON.parse(JSON.stringify(original));
copy.user.name = 'Bob';
console.log(original.user.name); // still "Alice"

Removing null values before sending

# Python — strip None values from a dict before serializing
import json

def remove_nulls(d):
    return {k: v for k, v in d.items() if v is not None}

data = {'name': 'Alice', 'email': None, 'age': 30}
print(json.dumps(remove_nulls(data)))
# {"name": "Alice", "age": 30}

Merging two JSON objects

// JavaScript — shallow merge (spread operator)
const defaults = { theme: 'light', lang: 'en', timeout: 30 };
const userPrefs = { theme: 'dark', lang: 'fr' };
const merged = { ...defaults, ...userPrefs };
// { theme: 'dark', lang: 'fr', timeout: 30 }

Quick Comparison

LanguageParse (string→object)Generate (object→string)Error type
JavaScriptJSON.parse(str)JSON.stringify(obj)SyntaxError
Pythonjson.loads(str)json.dumps(obj)json.JSONDecodeError
Java (Jackson)mapper.readValue()mapper.writeValueAsString()JsonProcessingException
PHPjson_decode(str)json_encode(obj)\JsonException

Related Resources

Use the JSON Formatter Hub to format, validate, and fix your JSON right now — free and fully browser-based.