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

JSON Formatter Hub

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

JSON parsing is one of the most common operations in any web application, API integration, or data pipeline. Every major programming language ships with built-in JSON support, but each has its own function names, error types, and gotchas. This guide shows you exactly how to read and write JSON in JavaScript, Python, Java, and PHP — with real code and the mistakes you need to avoid.

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)

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