Php json encoding objects

Encoding and Decoding of Json Objects Through PHP

As you know, JSON can be used with many programming languages; It is also popularly used with Java, PHP, and Python. In this tutorial, you will learn about the encoding and decoding of JSON objects through PHP. So, let us dig deep into it.

PHP json_decode and json_encode functions are used to decode and encode JSON object.

PHP JSON Functions

json_decode

PHP json_decode() function is used to decode JSON objects, and converts it into a PHP variable.

json_decode ($json [, $assoc = false [, $depth = 512 [, $options = 0 ]]])
'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>

This will produce the following results on executing:

object(stdClass)#1 (5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) > array(5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) >

json_encode

PHP json_encode() function is used to convert PHP array/objects into JSON value. this function returns JSON representation of a string if the function success or FALSE on failure.

string json_encode ( $value [, $options = 0 ] )

Example: Converting a PHP array to JSON:

 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?> 

This will produce the following results on executing:

Example: Converting PHP objects to JSON:

 $obj = new Employee(); $obj->name = 'Alex'; $obj->age = 24; $obj->role = 'PHP Developer'; echo json_encode($obj); ?>

This will produce the following results on executing:

Источник

json_encode

Возвращает строку, содержащую JSON-представление value .

Список параметров

value — значение, которое будет закодировано. Может быть любого типа за исключением resource .

Все строковые данные должны быть в кодировке UTF-8.

Замечание:

PHP реализует надмножество JSON, который описан в первоначальном » RFC 4627, — также кодируя и декодируя скалярные типы и NULL . RFC 4627 поддерживает эти значения только в случае, если они находятся внутри массива или объекта.

И хотя это надмножество согласуется с расширенным определением «JSON текста» из новых » RFC 7159 (который старается заменить собой RFC 4627) и » ECMA-404, это все равно может приводить к проблемам совместимости со старыми парсерами JSON, которые строго придерживаются RFC 4627 с кодированием скалярных значений.

Битовая маска составляемая из значений JSON_HEX_QUOT , JSON_HEX_TAG , JSON_HEX_AMP , JSON_HEX_APOS , JSON_NUMERIC_CHECK , JSON_PRETTY_PRINT , JSON_UNESCAPED_SLASHES , JSON_FORCE_OBJECT , JSON_UNESCAPED_UNICODE . Смысл этих констант объясняется на странице JSON констант.

Читайте также:  Node js scss to css

Задает максимальную глубину. Должен быть больше нуля.

Возвращаемые значения

Возвращает JSON закодированную строку ( string ) в случае успеха или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
5.5.0 Добавлен параметр depth .
5.4.0 В options были добавлены константы JSON_PRETTY_PRINT , JSON_UNESCAPED_SLASHES , и JSON_UNESCAPED_UNICODE .
5.3.3 Константа JSON_NUMERIC_CHECK была добавлена в option .
5.3.0 Был добавлен параметр options .

Примеры

Пример #1 Пример использования json_encode()

$arr = array( ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 , ‘d’ => 4 , ‘e’ => 5 );

Результат выполнения данного примера:

Пример #2 Пример использования json_encode() , показывающий действия некоторых его опций

echo «Обычно: » , json_encode ( $a ), «\n» ;
echo «Тэги: » , json_encode ( $a , JSON_HEX_TAG ), «\n» ;
echo «Апострофы: » , json_encode ( $a , JSON_HEX_APOS ), «\n» ;
echo «Кавычки: » , json_encode ( $a , JSON_HEX_QUOT ), «\n» ;
echo «Амперсанды: » , json_encode ( $a , JSON_HEX_AMP ), «\n» ;
echo «Юникод: » , json_encode ( $a , JSON_UNESCAPED_UNICODE ), «\n» ;
echo «Все: » , json_encode ( $a , JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE ), «\n\n» ;

echo «Отображение пустого массива как массива: » , json_encode ( $b ), «\n» ;
echo «Отображение пустого массива как объекта: » , json_encode ( $b , JSON_FORCE_OBJECT ), «\n\n» ;

echo «Отображение неассоциативного массива как массива: » , json_encode ( $c ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $c , JSON_FORCE_OBJECT ), «\n\n» ;

$d = array( ‘foo’ => ‘bar’ , ‘baz’ => ‘long’ );

echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d ), «\n» ;
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d , JSON_FORCE_OBJECT ), «\n\n» ;
?>

Результат выполнения данного примера:

Обычно: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Тэги: [«\u003Cfoo\u003E»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Апострофы: [«»,»\u0027bar\u0027″,»\»baz\»»,»&blong&»,»\u00e9″] Кавычки: [«»,»‘bar'»,»\u0022baz\u0022″,»&blong&»,»\u00e9″] Амперсанды: [«»,»‘bar'»,»\»baz\»»,»\u0026blong\u0026″,»\u00e9″] Unicode: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»é»] Все: [«\u003Cfoo\u003E»,»\u0027bar\u0027″,»\u0022baz\u0022″,»\u0026blong\u0026″,»é»] Отображение пустого массива как массива: [] Отображение не ассоциативного массива как объекта: <> Отображение неассоциативного массива как массива: [[1,2,3]] Отображение неассоциативного массива как объекта: > Ассоциативный массив всегда отображается как объект: Ассоциативный массив всегда отображается как объект:

Пример #3 Пример с последовательными индексами начинающимися с нуля и непоследовательными индексами массивов

echo «Последовательный массив» . PHP_EOL ;
$sequential = array( «foo» , «bar» , «baz» , «blong» );
var_dump (
$sequential ,
json_encode ( $sequential )
);

echo PHP_EOL . «Непоследовательный массив» . PHP_EOL ;
$nonsequential = array( 1 => «foo» , 2 => «bar» , 3 => «baz» , 4 => «blong» );
var_dump (
$nonsequential ,
json_encode ( $nonsequential )
);

echo PHP_EOL . «Последовательный массив с одним удаленным индексом» . PHP_EOL ;
unset( $sequential [ 1 ]);
var_dump (
$sequential ,
json_encode ( $sequential )
);
?>

Результат выполнения данного примера:

Последовательный массив array(4) < [0]=>string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(27) "["foo","bar","baz","blong"]" Непоследовательный массив array(4) < [1]=>string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=> string(5) "blong" > string(43) "" Последовательный массив с одним удаленным индексом array(3) < [0]=>string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(33) ""

Примечания

Замечание:

В случае ошибки кодирования, можно использовать json_last_error() для определения точной ошибки.

Замечание:

При кодировании массива в случае, если его индексы не являются последовательными числами от нуля, то все индексы кодируются в строковые ключи для каждой пары индекс-значение.

Замечание:

Как и эталонный кодировщик JSON, json_encode() будет создавать JSON в виде простого значения (т.е. не объект и не массив), если ему переданы string , integer , float или boolean в качестве входящего значения value . Большинство декодеров воспринимают эти значения как правильный JSON, но некоторые нет, потому что спецификация неоднозначна на этот счет.

Всегда проверяйте, что ваш JSON декодер может правильно обрабатывать данные, которые вы создаете с помощью json_encode() .

Смотрите также

  • JsonSerializable
  • json_decode() — Декодирует JSON строку
  • json_last_error() — Возвращает последнюю ошибку
  • serialize() — Генерирует пригодное для хранения представление переменной
Читайте также:  Html css slide menu

Источник

PHP JSON

Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.

JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.

JSON is built on two structures:

  • A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
  • An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.

The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.

PHP JSON extension

PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.

Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.

Converting PHP variables to JSON using json_encode() function

To get a JSON representation of a variable, you use the json_encode() function:

json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|falseCode language: PHP (php)

The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:

 $names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;Code language: PHP (php)
  • First, define an array of strings that consists of three elements.
  • Second, convert the array to JSON using the json_encode() function.
  • Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]Code language: JSON / JSON with Comments (json)

The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:

 $person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);Code language: PHP (php)
< name: "Alice", age: 20 >Code language: PHP (php)

In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.

Converting JSON data to PHP variables

To convert JSON data to a variable in PHP, you use the json_decode() function:

json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixedCode language: PHP (php)

The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:

 $json_data = ''; $person = json_decode($json_data); var_dump($person);Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) > Code language: PHP (php)

In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.

Serializing PHP objects

To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.

For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:

 class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);Code language: PHP (php)
"name":"Alice","age":20>Code language: PHP (php)
  • First, define a Person class that implements the JsonSerializable interface.
  • Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
  • Third, create a new Person object and serialize it to JSON data using the json_encode() function.

Summary

  • JSON is a lightweight data-interchange format.
  • Use the json_encode() function to convert PHP variables to JSON.
  • Use the json_decode() function to convert JSON data to PHP variables.
  • Implement the JsonSerializable interface to specify the JSON representation of an object.

Источник

Оцените статью