Data & Formats 9 min read

JSON Parser Guide: How to Parse JSON in Any Language

What a JSON parser does and how to parse JSON safely in Python, JavaScript, PHP, and more: nested data, big files, and typical errors, with code examples.

ST
Scraping.Pro Team
Data collection for business needs
Published: 3 December 2025

A JSON parser turns a string of JSON text into data structures your program can actually work with. This guide explains what JSON is, what a parser does, and how to parse JSON safely in every major language — including nested structures, streaming very large files, querying with JSONPath, and the mistakes that trip people up.

What JSON is

JSON (JavaScript Object Notation) is a text-based data-interchange format that's convenient for both humans to read and machines to process. Despite coming out of JavaScript, it long ago became a language-independent standard used almost everywhere applications need to exchange structured data.

A basic JSON document:

json
{
  "id": 42,
  "name": "Anna",
  "is_active": true,
  "roles": ["admin", "editor"],
  "profile": {
    "city": "Austin",
    "age": 29
  }
}

The format is built from a handful of simple types: objects (key–value pairs), arrays, strings, numbers, booleans, and null. That simplicity is exactly why it spread everywhere.

What JSON parsing is and why you need it

JSON parsing is the process of converting JSON text into a data structure your programming language understands: an object, dictionary, array, list, and so on. In essence, a parser takes a string of characters and turns it into live objects you can work with in code.

The reverse process — turning your program's objects back into a JSON string — is called serialization (or marshaling). Parsing and serialization almost always come as a pair.

Parsing shows up in typical tasks:

  • Working with APIs — sending and receiving data over HTTP (more on this below).
  • Configuration files — many tools store settings in JSON (package.json, tsconfig.json, and others).
  • Storing and exchanging data — logs, messages in queues (Kafka, RabbitMQ), documents in NoSQL databases (MongoDB).
  • Service-to-service communication in a microservice architecture.
  • Persisting application state to files or to localStorage in the browser.

JSON parsing when working with APIs

The most common scenario in which a developer hits JSON parsing is talking to an API. The overwhelming majority of modern web APIs (REST, and often other styles too) exchange data in JSON.

A typical API cycle looks like this:

  1. The client sends an HTTP request to an API endpoint.
  2. The server responds with a body that is a JSON string.
  3. The client parses that string into objects and works with the data.
  4. When sending data (POST, PUT), the client does the reverse and serializes its objects into JSON.

Without the parsing step, the server's response is just text you can't work with programmatically. That makes parsing a mandatory link in almost any integration with an external service — and the core skill behind API scraping, where you pull structured data straight from a site's JSON endpoints.

JSON parsing examples across languages

Below are examples of parsing JSON in popular languages. In each case we parse the same string and then read a nested field.

Python

The standard library includes the json module. loads parses a string; load parses the contents of a file. This built-in module is what people mean by a Python JSON parser — you rarely need anything else.

python
import json

data_str = '{"name": "Anna", "profile": {"city": "Austin", "age": 29}}'

# Parse a string into a dict
data = json.loads(data_str)

print(data["name"])              # Anna
print(data["profile"]["city"])   # Austin

# The reverse operation — serialization
back_to_str = json.dumps(data, ensure_ascii=False)

JavaScript

In JavaScript, parsing is built into the language via the global JSON object — it's the ecosystem's "native" format, so a dedicated JSON parser in JS is never needed.

javascript
const dataStr = '{"name": "Anna", "profile": {"city": "Austin", "age": 29}}';

// Parse a string into an object
const data = JSON.parse(dataStr);

console.log(data.name);            // Anna
console.log(data.profile.city);    // Austin

// The reverse operation
const backToStr = JSON.stringify(data);

When working with fetch, parsing the API response is a one-liner:

javascript
const response = await fetch("https://api.example.com/users/42");
const user = await response.json(); // response is already parsed into an object
console.log(user.name);

Java

The standard library has no built-in parser, so people typically use libraries — for example Jackson or Gson. With Jackson:

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

public class Main {
    public static void main(String[] args) throws Exception {
        String dataStr = "{\"name\": \"Anna\", \"profile\": {\"city\": \"Austin\"}}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(dataStr);

        System.out.println(node.get("name").asText());                  // Anna
        System.out.println(node.get("profile").get("city").asText());   // Austin
    }
}

More often, JSON is parsed straight into a typed class (a POJO):

java
record Profile(String city, int age) {}
record User(String name, Profile profile) {}

User user = mapper.readValue(dataStr, User.class);
System.out.println(user.profile().city());

Go

The standard library has the encoding/json package. Data is usually parsed into a struct with field tags.

go
package main

import (
    "encoding/json"
    "fmt"
)

type Profile struct {
    City string `json:"city"`
    Age  int    `json:"age"`
}

type User struct {
    Name    string  `json:"name"`
    Profile Profile `json:"profile"`
}

func main() {
    dataStr := `{"name": "Anna", "profile": {"city": "Austin", "age": 29}}`

    var user User
    json.Unmarshal([]byte(dataStr), &user)

    fmt.Println(user.Name)          // Anna
    fmt.Println(user.Profile.City)  // Austin
}

C

Modern .NET has the built-in System.Text.Json namespace.

c#
using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        string dataStr = "{\"name\": \"Anna\", \"profile\": {\"city\": \"Austin\"}}";

        using JsonDocument doc = JsonDocument.Parse(dataStr);
        JsonElement root = doc.RootElement;

        Console.WriteLine(root.GetProperty("name").GetString());                       // Anna
        Console.WriteLine(root.GetProperty("profile").GetProperty("city").GetString()); // Austin
    }
}

PHP

In PHP, parsing is built into the language via json_decode and json_encode.

php
<?php
$dataStr = '{"name": "Anna", "profile": {"city": "Austin", "age": 29}}';

// true — decode into an associative array rather than an object
$data = json_decode($dataStr, true);

echo $data["name"];             // Anna
echo $data["profile"]["city"];  // Austin

// The reverse operation
$backToStr = json_encode($data, JSON_UNESCAPED_UNICODE);

Rust

In the Rust ecosystem the de facto standard is the serde crate together with serde_json.

rust
use serde::Deserialize;

#[derive(Deserialize)]
struct Profile {
    city: String,
    age: u32,
}

#[derive(Deserialize)]
struct User {
    name: String,
    profile: Profile,
}

fn main() {
    let data_str = r#"{"name": "Anna", "profile": {"city": "Austin", "age": 29}}"#;

    let user: User = serde_json::from_str(data_str).unwrap();

    println!("{}", user.name);          // Anna
    println!("{}", user.profile.city);  // Austin
}

Comparing the approaches

Language Tool Built into the language
Python json Yes
JavaScript JSON Yes
Java Jackson / Gson No
Go encoding/json Yes
C# System.Text.Json Yes
PHP json_decode Yes
Rust serde / serde_json No

Two main approaches to parsing stand out:

  • Dynamic parsing — JSON becomes a generic structure (a dictionary, array, or tree of nodes). Convenient for quick, flexible work, but with no compile-time type checking.
  • Typed parsing — JSON is mapped straight into predefined classes or structs. Safer and clearer, especially in strongly typed languages (Java, Go, Rust, C#).

Parsing large JSON files (streaming)

Every example above loads the whole document into memory. That's fine for API responses of a few kilobytes, but it falls over on a multi-gigabyte export or a huge log file. For those, use a streaming (incremental) parser that reads the input piece by piece instead of all at once.

Pythonijson yields items as it reads, so memory stays flat:

python
import ijson

with open("huge.json", "rb") as f:
    # iterate over each element of a top-level "records" array
    for record in ijson.items(f, "records.item"):
        process(record)   # one object at a time, memory stays flat

Node.jsstream-json or Oboe.js do the same over a readable stream. Go — the built-in json.Decoder reads a stream token by token and can decode one array element per iteration. The pattern is universal: never hold more than one record in memory when the file is bigger than your RAM budget.

Querying JSON with JSONPath

Once a document is parsed, you often want to pull out just a few deep values without walking the tree by hand. JSONPath is a query language for JSON, much like XPath is for XML. An expression such as $.profile.city or $.roles[0] reaches straight into the structure.

python
# pip install jsonpath-ng
from jsonpath_ng import parse

expr = parse("$.profile.city")
matches = [m.value for m in expr.find(data)]
print(matches)   # ['Austin']

JSONPath libraries exist for every major language (jsonpath-ng in Python, jsonpath-plus in JS, and others), and most online JSON parser and validator tools let you test JSONPath expressions interactively — handy for exploring an unfamiliar API response before you write code.

Common problems and recommendations

When parsing JSON, watch out for a few typical pitfalls:

  • Invalid JSON. If the string is corrupted or has syntax errors, the parser throws. Always wrap the parsing of external data in error handling.
  • Missing or null fields. Don't assume every expected key is always present — an API may send back a partial object. Check that a field exists before you read it.
  • Encoding. JSON uses UTF-8 by the standard. In some languages (Python, PHP) you must set flags explicitly so that non-ASCII characters — accented letters, emoji, non-Latin scripts — aren't turned into \u escape sequences during serialization (ensure_ascii=False in Python, JSON_UNESCAPED_UNICODE in PHP).
  • Large documents. For very large files, use streaming parsing (see above) instead of loading the whole object into memory.
  • Numbers and precision. Large integers and floating-point numbers can lose precision — for financial data this is critical, and such values are sometimes transmitted as strings.

FAQ

What is a JSON parser? A component that reads JSON text and converts it into native data structures (objects, dictionaries, arrays) your code can use. Most languages ship one in their standard library.

What's the best JSON parser for Python? The built-in json module handles the vast majority of cases. For extreme performance, orjson is faster; for huge files, stream with ijson.

How do I parse JSON in JavaScript? Use JSON.parse(string) for text, or await response.json() when reading a fetch response — both are built into the language.

Is there a good JSON parser online? Yes — browser-based validators and formatters let you paste JSON to check syntax, pretty-print it, and test JSONPath queries without writing any code. They're great for debugging, but never paste sensitive or proprietary data into a third-party site.

Wrap-up

JSON parsing is a foundational skill — without it, working with modern APIs and exchanging data between systems is nearly impossible. The format is universal, and every common language has tools to parse it, whether built in or as a popular library. The principle is the same everywhere: turn a text string into objects your code can use, and reverse the trip when needed.

If your goal is to collect JSON at scale — say, harvesting product or listing data from dozens of site APIs — that's exactly the plumbing scraping.pro handles as a data extraction service: endpoint discovery, pagination, authentication, and clean structured output. To see how parsing fits into the full request cycle, read our companion piece on API scraping.