라이브러리

[PHP] json_decode - JSON 문자열을 디코딩합니다.




JSON Decode (JSON 디코딩)
==========================

JSON (JavaScript Object Notation) 디코딩은 JSON 데이터를 PHP의 데이터 타입으로 변환하는 과정입니다. PHP의 `json_decode()` 함수를 사용하여 JSON 데이터를 디코딩할 수 있습니다.

json_decode() 함수
-------------------

`json_decode()` 함수는 두 개의 매개변수를 받습니다.

* `json` : 디코딩할 JSON 데이터
* `associative` (옵션) : 디코딩 결과가 연관 배열인지 여부를 결정합니다. 기본값은 `false`입니다.

예제
------

예제 1: 기본 디코딩


#hostingforum.kr
php

$json_data = '{"name": "John", "age": 30, "city": "Seoul"}';



$data = json_decode($json_data);



print_r($data);



출력:

#hostingforum.kr
php

stdClass Object

(

    [name] => John

    [age] => 30

    [city] => Seoul

)



예제 2: 연관 배열로 디코딩


#hostingforum.kr
php

$json_data = '{"name": "John", "age": 30, "city": "Seoul"}';



$data = json_decode($json_data, true);



print_r($data);



출력:

#hostingforum.kr
php

Array

(

    [name] => John

    [age] => 30

    [city] => Seoul

)



예제 3: 디코딩 오류 처리


#hostingforum.kr
php

$json_data = '{"name": "John", "age": 30, "city": "Seoul"}';



$data = json_decode($json_data, true);



if (json_last_error() !== JSON_ERROR_NONE) {

    echo "디코딩 오류: " . json_last_error_msg();

} else {

    print_r($data);

}



출력:

#hostingforum.kr
php

디코딩 오류: Syntax error



예제 4: JSON 데이터가 없는 경우


#hostingforum.kr
php

$json_data = '';



$data = json_decode($json_data, true);



if (json_last_error() !== JSON_ERROR_NONE) {

    echo "디코딩 오류: " . json_last_error_msg();

} else {

    print_r($data);

}



출력:

#hostingforum.kr
php

디코딩 오류: Unexpected end of JSON input



참고
------

* `json_decode()` 함수는 JSON 데이터를 디코딩할 때 `JSON_ERROR_NONE` 오류 코드를 반환합니다.
* `json_last_error()` 함수를 사용하여 디코딩 오류를 확인할 수 있습니다.
* `json_last_error_msg()` 함수를 사용하여 디코딩 오류 메시지를 확인할 수 있습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 1 페이지

검색

게시물 검색