JSON json_decode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_decode — JSON 문자열을 디코딩합니다.


설명

json_decode(
    string $json,
    ?bool $associative = null,
    int $depth = 512,
    int $flags = 0
): mixed
                

JSON으로 인코딩된 문자열을 가져와 PHP 변수로 변환합니다.


매개변수

json
디코딩 중인 json 문자열입니다.

이 함수는 UTF-8로 인코딩된 문자열에서만 작동합니다.

메모: PHP는 원래 » RFC 7159에 지정된 대로 JSON의 상위 집합을 구현합니다.

associative
true이면 JSON 객체가 연관 배열로 반환됩니다. false인 경우 JSON 객체가 객체로 반환됩니다. null인 경우 JSON_OBJECT_AS_ARRAYflags에 설정되었는지 여부에 따라 JSON 객체가 연관 배열 또는 객체로 반환됩니다.
depth
디코딩되는 구조의 최대 중첩 깊이입니다.
flags
JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR의 비트마스크. 이러한 상수의 동작은 JSON constants 페이지에 설명되어 있습니다.

반환 값

적절한 PHP 유형의 json으로 인코딩된 값을 반환합니다. true, falsenull 값은 각각 true, falsenull로 반환됩니다. json을 디코딩할 수 없거나 인코딩된 데이터가 중첩 제한보다 깊은 경우 null이 반환됩니다.


변경 로그

버전 설명
7.3.0 JSON_THROW_ON_ERROR flags가 추가되었습니다.
7.2.0 associative은 이제 nullable입니다.
7.2.0 JSON_INVALID_UTF8_IGNOREJSON_INVALID_UTF8_SUBSTITUTE flags가 추가되었습니다.
7.1.0 값이 _empty_인 키를 사용하는 대신 빈 JSON 키("")를 빈 개체 속성으로 인코딩할 수 있습니다.

Examples

예제 #1 json_decode() 예제

                  
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>
                  
                

위의 예는 다음을 출력합니다.

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)
}
                

예제 #2 잘못된 개체 속성에 액세스

PHP의 명명 규칙(예: 하이픈)에 따라 허용되지 않는 문자를 포함하는 개체 내의 요소에 액세스하려면 요소 이름을 중괄호와 아포스트로피로 캡슐화하여 수행할 수 있습니다.

                  
<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>
                  
                

예제 #3 json_decode()를 사용하는 일반적인 실수

                  
<?php

// 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

?>
                  
                

예제 #4 depth errors

                  
<?php
// 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'
            )
        )
    )
);

// 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;
?>
                  
                

위의 예는 다음을 출력합니다.

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
                

예제 #5 큰 정수의 json_decode()

                  
<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>
                  
                

위의 예는 다음을 출력합니다.

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}
                

메모

메모: JSON 사양은 JavaScript가 아니라 JavaScript의 하위 집합입니다.

메모: 디코딩에 실패한 경우 json_last_error()를 사용하여 오류의 정확한 특성을 확인할 수 있습니다.


기타