차근차근/PHP

유용한 함수 - json_decode,json_encode

예쁜꽃이피었으면 2014. 9. 2. 01:12

http://www.freeimage.kr/bbs/board.php?bo_table=tip_php&wr_id=803&sst=wr_hit&sod=asc&page=6


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


이번에 올리는 함수는 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 데이타는 이함수를 통해서 얼마든지 이용할수 있습니다.



----------------------------

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

반응형