Quick Jump
The Universal JSON Cheat Sheet
Every language handles JSON slightly differently. This guide gives you copy-paste ready code for reading JSON files and parsing JSON strings in all major programming languages.
Each example covers three scenarios:
- Parse a JSON string — When you have JSON as a string variable
- Read a JSON file — When JSON is stored in a file
- Fetch JSON from an API — When JSON comes from a web request
JavaScript / Node.js
JavaScript has native JSON support — no libraries needed.
Parse a JSON String
const jsonString = '{"name": "Alice", "age": 30, "active": true}';
// Parse JSON string to object
const data = JSON.parse(jsonString);
console.log(data.name); // "Alice"
console.log(data.age); // 30
console.log(data.active); // true Read a JSON File (Node.js)
const fs = require('fs');
// Synchronous (blocking)
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
// Asynchronous (recommended)
const fsPromises = require('fs').promises;
async function readJsonFile(path) {
const content = await fsPromises.readFile(path, 'utf8');
return JSON.parse(content);
}
// Usage
const data = await readJsonFile('data.json'); Fetch JSON from API
// Browser or Node.js 18+
const response = await fetch('https://api.example.com/users');
const data = await response.json();
// With error handling
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
const users = await fetchJson('https://api.example.com/users'); Python
Python's json module is part of the standard library.
Parse a JSON String
import json
json_string = '{"name": "Alice", "age": 30, "active": true}'
# Parse JSON string to dictionary
data = json.loads(json_string)
print(data['name']) # Alice
print(data['age']) # 30
print(data['active']) # True (note: Python uses True, not true) Read a JSON File
import json
# Read and parse JSON file
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# Access nested data
print(data['users'][0]['name'])
# With error handling
def read_json_file(path):
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"File not found: {path}")
return None
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
return None Fetch JSON from API
import requests # pip install requests
# Simple GET request
response = requests.get('https://api.example.com/users')
data = response.json()
# With headers and error handling
def fetch_json(url, headers=None):
response = requests.get(url, headers=headers)
response.raise_for_status() # Raises exception for 4xx/5xx
return response.json()
users = fetch_json('https://api.example.com/users') Java
Java doesn't have built-in JSON support. Use Jackson (most popular) or Gson.
Using Jackson
<!-- Add to your pom.xml -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency> import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.File;
import java.io.IOException;
public class JsonReader {
private static final ObjectMapper mapper = new ObjectMapper();
// Parse JSON string
public static JsonNode parseString(String json) throws IOException {
return mapper.readTree(json);
}
// Read JSON file
public static JsonNode readFile(String path) throws IOException {
return mapper.readTree(new File(path));
}
// Parse to POJO (Plain Old Java Object)
public static <T> T parseToObject(String json, Class<T> clazz) throws IOException {
return mapper.readValue(json, clazz);
}
public static void main(String[] args) throws IOException {
String json = "{\"name\": \"Alice\", \"age\": 30}";
JsonNode node = parseString(json);
System.out.println(node.get("name").asText()); // Alice
System.out.println(node.get("age").asInt()); // 30
}
} Using Gson
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.FileReader;
public class GsonExample {
private static final Gson gson = new Gson();
public static void main(String[] args) throws Exception {
// Parse JSON string
String json = "{\"name\": \"Alice\", \"age\": 30}";
JsonObject obj = gson.fromJson(json, JsonObject.class);
System.out.println(obj.get("name").getAsString());
// Read from file
JsonObject data = gson.fromJson(new FileReader("data.json"), JsonObject.class);
// Parse to POJO
User user = gson.fromJson(json, User.class);
}
} C# / .NET
.NET 5+ has built-in System.Text.Json. For older versions, use Newtonsoft.Json.
Using System.Text.Json (.NET 5+)
using System;
using System.IO;
using System.Text.Json;
using System.Net.Http;
using System.Threading.Tasks;
public class JsonReader
{
// Parse JSON string
public static JsonDocument ParseString(string json)
{
return JsonDocument.Parse(json);
}
// Read JSON file
public static async Task<JsonDocument> ReadFileAsync(string path)
{
string content = await File.ReadAllTextAsync(path);
return JsonDocument.Parse(content);
}
// Deserialize to object
public static T Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json);
}
// Fetch from API
public static async Task<T> FetchJsonAsync<T>(string url)
{
using var client = new HttpClient();
var response = await client.GetStringAsync(url);
return JsonSerializer.Deserialize<T>(response);
}
public static void Main()
{
string json = "{\"name\": \"Alice\", \"age\": 30}";
using var doc = ParseString(json);
var root = doc.RootElement;
Console.WriteLine(root.GetProperty("name").GetString()); // Alice
Console.WriteLine(root.GetProperty("age").GetInt32()); // 30
}
} Using Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
// Parse JSON string
string json = "{\"name\": \"Alice\", \"age\": 30}";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["name"]); // Alice
// Deserialize to object
var user = JsonConvert.DeserializeObject<User>(json);
// Read from file
var data = JObject.Parse(File.ReadAllText("data.json")); Go
Go has excellent JSON support in the standard library via encoding/json.
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
// Define struct for typed parsing
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Active bool `json:"active"`
}
func main() {
// Parse JSON string to struct
jsonStr := `{"name": "Alice", "age": 30, "active": true}`
var user User
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
panic(err)
}
fmt.Println(user.Name) // Alice
// Parse to map (dynamic)
var data map[string]interface{}
json.Unmarshal([]byte(jsonStr), &data)
fmt.Println(data["name"]) // Alice
// Read from file
file, _ := os.ReadFile("data.json")
var fileData User
json.Unmarshal(file, &fileData)
// Fetch from API
resp, _ := http.Get("https://api.example.com/users")
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var users []User
json.Unmarshal(body, &users)
} PHP
PHP has built-in JSON functions since version 5.2.
<?php
// Parse JSON string
$jsonString = '{"name": "Alice", "age": 30, "active": true}';
// As object (default)
$data = json_decode($jsonString);
echo $data->name; // Alice
// As associative array
$data = json_decode($jsonString, true);
echo $data['name']; // Alice
// Read from file
$fileContent = file_get_contents('data.json');
$data = json_decode($fileContent, true);
// With error handling
function parseJson($json) {
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('JSON parse error: ' . json_last_error_msg());
}
return $data;
}
// Fetch from API
$response = file_get_contents('https://api.example.com/users');
$users = json_decode($response, true);
// Using cURL for more control
function fetchJson($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
?> Ruby
Ruby's json library is part of the standard library.
require 'json'
require 'net/http'
require 'uri'
# Parse JSON string
json_string = '{"name": "Alice", "age": 30, "active": true}'
data = JSON.parse(json_string)
puts data['name'] # Alice
puts data['age'] # 30
puts data['active'] # true
# Parse with symbol keys (common in Rails)
data = JSON.parse(json_string, symbolize_names: true)
puts data[:name] # Alice
# Read from file
data = JSON.parse(File.read('data.json'))
# With error handling
def parse_json_file(path)
JSON.parse(File.read(path))
rescue Errno::ENOENT
puts "File not found: #{path}"
nil
rescue JSON::ParserError => e
puts "Invalid JSON: #{e.message}"
nil
end
# Fetch from API
uri = URI('https://api.example.com/users')
response = Net::HTTP.get(uri)
users = JSON.parse(response)
# With headers
uri = URI('https://api.example.com/users')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer token'
response = http.request(request)
data = JSON.parse(response.body) Rust
Rust uses the serde ecosystem for JSON serialization.
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] } use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::fs;
#[derive(Debug, Serialize, Deserialize)]
struct User {
name: String,
age: u32,
active: bool,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let json_str = r#"{"name": "Alice", "age": 30, "active": true}"#;
// Parse to struct (typed)
let user: User = serde_json::from_str(json_str)?;
println!("{}", user.name); // Alice
// Parse to dynamic Value
let value: Value = serde_json::from_str(json_str)?;
println!("{}", value["name"]); // "Alice"
// Read from file
let content = fs::read_to_string("data.json")?;
let data: User = serde_json::from_str(&content)?;
Ok(())
}
// Async API fetch (with reqwest)
async fn fetch_users() -> Result<Vec<User>, reqwest::Error> {
let users = reqwest::get("https://api.example.com/users")
.await?
.json::<Vec<User>>()
.await?;
Ok(users)
} Quick Comparison Table
| Language | Parse String | Read File | Library |
|---|---|---|---|
| JavaScript | JSON.parse(str) | fs.readFileSync() | Built-in |
| Python | json.loads(str) | json.load(file) | Built-in |
| Java | mapper.readTree(str) | mapper.readTree(file) | Jackson |
| C# | JsonDocument.Parse(str) | File.ReadAllText() | System.Text.Json |
| Go | json.Unmarshal() | os.ReadFile() | encoding/json |
| PHP | json_decode($str) | file_get_contents() | Built-in |
| Ruby | JSON.parse(str) | File.read() | Built-in |
| Rust | serde_json::from_str() | fs::read_to_string() | serde_json |
What's Next?
Now you can read JSON in any language. Here's where to go from here:
- Handle large JSON files without crashing
- Validate JSON with JSON Schema
- Fix common JSON parsing errors
- Try our JSON tools — format and validate JSON instantly
Bookmark this page. You'll be back.