JSON Format in PHP
JSON is a format for storing data. This format is often used for data exchange between websites, or between a server and a browser. This format is more compact and simpler compared to XML, which is why it is now used much more widely.
The abbreviation JSON stands for JavaScript Object Notation. The fact is that JSON was originally invented in the JavaScript language, but is now used everywhere.
From PHP's point of view, data in JSON format is represented as a string:
<?php
$str = '
// JSON will be here
';
?>
The format itself is a kind of
multidimensional structure consisting
of regular and associative arrays.
Array elements can be strings
(necessarily in double quotes), numbers,
values true
, false
or null
.
Let's look at some examples. Let's create an array with numbers:
<?php
$str = '[1, 2, 3, 4, 5]';
?>
Let's create an array with strings:
<?php
$str = '["a", "b", "c"]';
?>
Let's create an array with mixed content:
<?php
$str = '[1, "a", true, false, null]';
?>
Now let's create an associative array. In JavaScript terms, such arrays are called objects. Objects are enclosed in curly braces, and keys are separated from values by colons. In this case, the keys of such arrays must be strings, always in double quotes. Let's create an example of an object:
<?php
$str = '{
"a": 1,
"b": 2,
"c": 3
}';
?>
You can combine arrays and objects in structures of any nesting level:
<?php
$str = '{
"a": [1, 2, 3],
"b": [4, 5, 6]
}';
?>
Note that trailing commas after the last element are not allowed in the JSON format:
<?php
$str = '[
"a",
"b",
"c",
]'; // last comma is redundant
?>
Convert the following PHP structure into a JSON string:
<?php
$data = [1, 2, 3];
?>
Convert the following PHP structure into a JSON string:
<?php
$data = ['x', 'y', 'z',];
?>
Convert the following PHP structure into a JSON string:
<?php
$data = [
'x' => 'a',
'y' => 'b',
'z' => 'c',
];
?>
Convert the following PHP structure into a JSON string:
<?php
$data = [
'ru' => ['1', '2', '3'],
'en' => ['a', 'b', 'c'],
];
?>