JSON (JavaScript Object Notation) is a standardized, lightweight text format for data exchange across different systems, backend servers, web browsers, and microcontrollers. Due to its clean syntax, it is human-readable and fast for machines to parse. In this guide, we explore core syntax rules, data types, and integration examples across JavaScript, PHP, MySQL, and Arduino/ESP devices.
Supported JSON Data Types
JSON supports a concise set of universal data types natively recognized by virtually all modern programming languages.
| Data Type | Format Description | Example Syntax |
|---|---|---|
| String | Text wrapped in mandatory double quotes | "Sensor 1" |
| Number | Integer or floating point without quotes | 42 or 23.4 |
| Boolean | True or false logical state | true or false |
| Array | Ordered list of values in square brackets | [21.5, 22.0, 21.8] |
| Object | Key-value pairs enclosed in curly braces | {"room": "Workshop"} |
| Null | Represents empty or non-existent value | null |
Structured JSON Data Example
The snippet below shows a valid JSON object combining multiple data types to represent a hardware telemetry payload.
{
"device": "Living Room Sensor",
"id": 104,
"active": true,
"readings": [21.5, 22.0, 21.8],
"location": {
"room": "Living room",
"floor": 1
},
"notes": null
}
Working with JSON in JavaScript and PHP
Browsers process JSON natively via the built-in JSON object and the fetch() API, while backend PHP scripts handle encoding and decoding for RESTful endpoints.
// --- JAVASCRIPT: Encoding and parsing JSON ---
const user = { name: "Borut", role: "admin" };
const jsonString = JSON.stringify(user); // Object to string
const rawData = '{"temperature": 23.4, "humidity": 55}';
const telemetry = JSON.parse(rawData); // String to JS object
console.log(telemetry.temperature); // Output: 23.4
<?php
// --- PHP: Reading and emitting JSON responses ---
header('Content-Type: application/json; charset=utf-8');
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);
$response = [
"status" => "success",
"timestamp" => date("Y-m-d H:i:s"),
"results" => [
["id" => 1, "name" => "Relay 1", "state" => true],
["id" => 2, "name" => "Relay 2", "state" => false]
]
];
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
?>
Common JSON Syntax Pitfalls
When hand-crafting or generating JSON payloads, keep these essential validation constraints in mind:
- Single Quotes: Keys and string values must strictly use double quotes (
"). Single quotes (') trigger parser failures. - Trailing Commas: The last entry in an array or object must never be followed by a comma.
- Comments: The JSON specification strictly forbids comments (such as
//or/* */). - Unescaped Characters: Special characters (like double quotes inside string values) must be escaped (
\",\n).