유용한 함수 - json_decode > 개발자팁

개발자팁

개발과 관련된 유용한 정보를 공유하세요.
질문은 QA에서 해주시기 바랍니다.

유용한 함수 - json_decode 정보

PHP 유용한 함수 - json_decode

본문

안녕하세요 유창화입니다.

이번에 올리는 함수는 json_decode 입니다.
물론, json_encode 와 한쌍입니다.

그런데 왜, json_decode 로 제목을 정했냐하면......
제가 더 많이 쓰기 때문입니다.

요새는 ajax 가 일반적인 기술이 되었습니다.
ajax에서 데이타를 주고 받을때 주로 json 을 많이 이용합니다.
json 데이타를 php에서도 바로 받아서 활용할수 있게 만드는 함수가 json_decode 입니다.

어떻게 보면 내용은 변수를 일렬화 시키고 복구 한다는 차원에서는
serialize, unserialize 와 비슷합니다.

그러나, 일반적인 방법으로 자바스크립트와 같이 동시에 쓸수 있다는 점이 다릅니다.

{"title":"\uc544\ub984\ub2e4\uc6b4 \uc6b0\ub9ac\ub098\ub77c","content":"\uc5b4\uca4c\uad6c \uc800\uca4c\uad6c......"}

이런 데이타가 저장된 a.txt 라는 파일이 있다면

$text = file_get_contents('a.txt');
$a = json_decode($text);
print_r($a);

stdClass Object
(
    [title] => 아름다운 우리나라
    [content] => 어쩌구 저쩌구......
)

와 같이 반환 됩니다.

보시면 알겟지만 stdClass Object
이렇게 되어있습니다. 즉, 객체로 반환됩니다.

참고로 알아야 할 사항은
json_encode 나 json_decode 나 데이타는 모두 utf-8 형태이어야 합니다.


포탈의 서비스 중
공개된 json 데이타는 이함수를 통해서 얼마든지 이용할수 있습니다.




추천
7

댓글 14개

외람된 질문이지만,, php 5.2 이상에서만 사용가능한 함수라고 본것같아서요..
5.2이상에서만 사용가능한건가요..?!
그렇다면.. 혹.. 그 이하 버전에는 개인적으로 쓰려고 만들어둔 함수가 혹시 있나 싶어서요..ㅋ
저도 추천 드려요!ㅋ
//json_encode
if(!function_exists('json_encode')){

    function json_encode($a=false){

        if(is_null($a)) return 'null';
        if($a === false) return 'false';
        if($a === true) return 'true';
        if(is_scalar($a)){

            if(is_float($a)) return floatval(str_replace(",", ".", strval($a)));
            if(is_string($a)){

                static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            else return $a;
        }

        $isList = true;
        for($i=0, reset($a); $i<count($a); $i++, next($a)){

            if(key($a) !== $i){

                $isList = false;
                break;
            }
        }
        $result = array();
        if($isList){

            foreach($a as $v) $result[] = json_encode($v);
            return '[' . join(',', $result) . ']';
        }
        else{

            foreach($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);

            return '{' . join(',', $result) . '}';
        }
    }
}



if (!function_exists('json_decode')){

    function json_decode($json) {

        $comment = false;
        $out = '$x=';

        for ($i=0; $i<strlen($json); $i++)  {

            if (!$comment) {

                if ($json[$i] == '{') $out .= ' array(';
                else if ($json[$i] == '}') $out .= ')';
                else if ($json[$i] == ':') $out .= '=>';
                else $out .= $json[$i];
            }
            else {

                $out .= $json[$i];
            }

            if ($json[$i] == '"') $comment = !$comment;
        }

        eval($out . ';');

        return $x;
    }
}
if (!function_exists('json_decode')){

    function json_decode($json){

        $comment = false;
        $out = '$x=';

        for ($i=0; $i<strlen($json); $i++){

            if (!$comment){

                if (($json[$i] == '{') || ($json[$i] == '['))
                    $out .= ' array(';
                else if (($json[$i] == '}') || ($json[$i] == ']')) 
                    $out .= ')';
                else if ($json[$i] == ':')   
                    $out .= '=>';
                else                       
                    $out .= $json[$i];       
            }
            else {
               
                $out .= $json[$i];
            }

            if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
        }
        eval($out . ';');

        return $x;
    }
}

이게 더 정확한듯 합니다.
추천합니다.
\uc544\ub984\ub2e4\uc6b4 \uc6b0\ub9ac\ub098\ub77c이런 것은 무슨 암호화인가요?
써제스트하면서 json을 자세히 보았는데 {"id": "아이디", "value": "값", "info": "설명"} 처럼 암호화 없이 바로 쓰더라구요.
전체 28
개발자팁 내용 검색 PHP에서

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1402호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT