json_decode
Takes a JSON encoded string and converts it into a PHP value.
Parameters
The json string being decoded.
This function only works with UTF-8 encoded strings.
Note:
PHP implements a superset of JSON as specified in the original » RFC 7159.
associative
When true , JSON objects will be returned as associative array s; when false , JSON objects will be returned as object s. When null , JSON objects will be returned as associative array s or object s depending on whether JSON_OBJECT_AS_ARRAY is set in the flags .
Maximum nesting depth of the structure being decoded. The value must be greater than 0 , and less than or equal to 2147483647 .
Bitmask of JSON_BIGINT_AS_STRING , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_OBJECT_AS_ARRAY , JSON_THROW_ON_ERROR . The behaviour of these constants is described on the JSON constants page.
Return Values
Returns the value encoded in json as an appropriate PHP type. Unquoted values true , false and null are returned as true , false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.
Errors/Exceptions
If depth is outside the allowed range, a ValueError is thrown as of PHP 8.0.0, while previously, an error of level E_WARNING was raised.
Changelog
| Version | Description |
|---|---|
| 7.3.0 | JSON_THROW_ON_ERROR flags was added. |
| 7.2.0 | associative is nullable now. |
| 7.2.0 | JSON_INVALID_UTF8_IGNORE , and JSON_INVALID_UTF8_SUBSTITUTE flags were added. |
| 7.1.0 | An empty JSON key («») can be encoded to the empty object property instead of using a key with value _empty_ . |
Examples
Example #1 json_decode() examples
var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , true ));
The above example will output:
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) >
Example #2 Accessing invalid object properties
Accessing elements within an object that contain characters not permitted under PHP’s naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.
$obj = json_decode ( $json );
print $obj ->< 'foo-bar' >; // 12345
Example #3 common mistakes using json_decode()
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = «< 'bar': 'baz' >» ;
json_decode ( $bad_json ); // null
// the name must be enclosed in double quotes
$bad_json = ‘< bar: "baz" >‘ ;
json_decode ( $bad_json ); // null
// trailing commas are not allowed
$bad_json = ‘< bar: "baz", >‘ ;
json_decode ( $bad_json ); // null
Example #4 depth errors
// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode (
array(
1 => array(
‘English’ => array(
‘One’ ,
‘January’
),
‘French’ => array(
‘Une’ ,
‘Janvier’
)
)
)
);
?php
// Show the errors for different depths.
var_dump ( json_decode ( $json , true , 4 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
var_dump ( json_decode ( $json , true , 3 ));
echo ‘Last error: ‘ , json_last_error_msg (), PHP_EOL , PHP_EOL ;
?>
The above example will output:
array(1) < [1]=>array(2) < ["English"]=>array(2) < [0]=>string(3) "One" [1]=> string(7) "January" > ["French"]=> array(2) < [0]=>string(3) "Une" [1]=> string(7) "Janvier" > > > Last error: No error NULL Last error: Maximum stack depth exceeded
Example #5 json_decode() of large integers
var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , false , 512 , JSON_BIGINT_AS_STRING ));
The above example will output:
object(stdClass)#1 (1) < ["number"]=>float(1.2345678901235E+19) > object(stdClass)#1 (1) < ["number"]=>string(20) "12345678901234567890" >
Notes
Note:
The JSON spec is not JavaScript, but a subset of JavaScript.
Note:
In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
See Also
- json_encode() — Returns the JSON representation of a value
- json_last_error() — Returns the last error occurred
User Contributed Notes 8 notes
1 year ago
JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a «list» or «object» when converted to/from JSON, depending on the keys (of absence of them).
You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:
$json = »;
$array = json_decode($json, true); // decode as associative hash
print json_encode($array) . PHP_EOL;
This will output a different JSON string than the original:
The object has turned into an array!
Similarly, a array that doesn’t have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.
$array = [
‘first’,
‘second’,
‘third’,
];
print json_encode($array) . PHP_EOL;
// remove the second element
unset($array[1]);
print json_encode($array) . PHP_EOL;
The output will be:
The array has turned into an object!
In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!
On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.
Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.
If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:
If you want to enforce an array to encode to a JSON object, use:
Работа с JSON в PHP
JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар . Значение может быть массивом, числом, строкой и булевым значением.
В PHP поддержка JSON появилась с версии 5.2.0 и работает только с кодировкой UTF-8.
Кодирование
json_encode($value, $options) – кодирует массив или объект в JSON.
$array = array( '1' => 'Значение 1', '2' => 'Значение 2', '3' => 'Значение 3', '4' => 'Значение 4', '5' => 'Значение 5' ); $json = json_encode($array); echo $json;
Как видно кириллица кодируется, исправляется это добавлением опции JSON_UNESCAPED_UNICODE .
$json = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json;
Далее такую строку можно сохранить в файл, или отдать в браузер, например при AJAX запросах.
header('Content-Type: application/json'); echo $json; exit();
Декодирование
Функция json_decode($json) преобразует строку в объект:
$json = ''; $array = json_decode($json); print_r($array);
stdClass Object ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )
Если добавить вторым аргументом true , то произойдёт преобразование в массив:
$json = ''; $array = json_decode($json, true); print_r($array);
Array ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )
Получение ошибок и их исправление
json_decode() возвращает NULL , если в объекте есть ошибки, посмотреть их можно с помощью функции json_last_error() :
$json = ''; $array = json_decode($json, true); switch (json_last_error())
Посмотреть значения констант JSON:
$constants = get_defined_constants(true); foreach ($constants['json'] as $name => $value) < echo $name . ': ' . $value . '
'; >
JSON_HEX_TAG: 1 JSON_HEX_AMP: 2 JSON_HEX_APOS: 4 JSON_HEX_QUOT: 8 JSON_FORCE_OBJECT: 16 JSON_NUMERIC_CHECK: 32 JSON_UNESCAPED_SLASHES: 64 JSON_PRETTY_PRINT: 128 JSON_UNESCAPED_UNICODE: 256 JSON_PARTIAL_OUTPUT_ON_ERROR: 512 JSON_PRESERVE_ZERO_FRACTION: 1024 JSON_UNESCAPED_LINE_TERMINATORS: 2048 JSON_OBJECT_AS_ARRAY: 1 JSON_BIGINT_AS_STRING: 2 JSON_ERROR_NONE: 0 JSON_ERROR_DEPTH: 1 JSON_ERROR_STATE_MISMATCH: 2 JSON_ERROR_CTRL_CHAR: 3 JSON_ERROR_SYNTAX: 4 JSON_ERROR_UTF8: 5 JSON_ERROR_RECURSION: 6 JSON_ERROR_INF_OR_NAN: 7 JSON_ERROR_UNSUPPORTED_TYPE: 8 JSON_ERROR_INVALID_PROPERTY_NAME: 9 JSON_ERROR_UTF16: 10
Если вы хотите распарсить JS объект из HTML страницы или файла, то скорее всего json_decode вернет ошибку т.к. в коде будут управляющие символы или BOM. Удалить их можно следующим образом:
$json = ''; // Удаление управляющих символов for ($i = 0; $i // Удаление символа Delete $json = str_replace(chr(127), '', $json); // Удаление BOM if (0 === strpos(bin2hex($json), 'efbbbf')) < $json = substr($json, 3); >$res = json_decode($json, true); print_r($res);
HTTP-запросы в формате JSON
Некоторые сервисы требуют чтобы запросы к ним осуществлялись в формате JSON, такой запрос можно сформировать в CURL:
$data = array( 'name' => 'snipp.ru' 'text' => 'Отправка сообщения', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $res = curl_exec($ch); curl_close($ch);
А также могут обратится к вашим скриптам в таком формате, чтение JSON запроса.
$data = file_get_contents('php://input'); $data = json_decode($data, true);
Как PHP получить получить JSON из JAVASCRIPT?
Решил записывать приходящее содержимое в текстовый файл и на выходе получил null. Отправлял запрос с помощью reqbin и смог получить ответ.
Для отправки со стороны JS пробовал использовать сгенерированный этим же сервисом код, но результата это не дало.
var url = "/conference/api"; var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.onreadystatechange = function () < if (xhr.readyState === 4) < console.log(xhr.status); console.log(xhr.responseText); >>; var data = ''; xhr.send(data);
- Вопрос задан 29 нояб. 2022
- 140 просмотров
1 комментарий
Средний 1 комментарий
jQuery.get()
jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
Description: Load data from the server using a HTTP GET request.
version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
url
A string containing the URL to which the request is sent.
data
A plain object or string that is sent to the server with the request.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder.
dataType
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
version added: 1.12-and-2.2 jQuery.get( [settings ] )
settings
A set of key/value pairs that configure the Ajax request. All properties except for url are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. The type option will automatically be set to GET .
This is a shorthand Ajax function, which is equivalent to:
$.ajax(url: url,data: data,success: success,dataType: dataType>);
The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.
As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR , in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
Most implementations will specify a success handler:
$.get( "ajax/test.html", function( data )$( ".result" ).html( data );alert( "Load was performed." );>);
This example fetches the requested HTML snippet and inserts it on the page.
The jqXHR Object
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
The Promise interface also allows jQuery's Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
