레이블이 json인 게시물을 표시합니다. 모든 게시물 표시
레이블이 json인 게시물을 표시합니다. 모든 게시물 표시

2009년 2월 13일 금요일

json encode util사용

javascript에서 json으로 data passing

aa = ["한글", "id", "contactId", "fullName"];
_params['test']       = Ext.util.JSON.encode( aa );
껌임.

헌데 여기서 엄청난 사질이 있었음...
php쪽

$test = stripslashes( iconv('utf-8', 'cp949', $test ) );
print_r ( json_decode( $test ) )
stripslahses안 해주면 decode안됨

2009년 2월 12일 목요일

모듈명.api.php 사용 가능 함

Ajax를 사용하기 위해 제 3의 기능이 탄생했습니다.
ModuleObject.class.php에 가장 밑에 추가된 기능이네요.

          
// view action이고 결과 출력이 XMLRPC일 경우 해당 모듈의 api method를 실행
            if($this->module_info->module_type == 'view'){
                if(Context::getResponseMethod() == 'XMLRPC' || Context::getResponseMethod() == 'JSON') {
                    $oAPI = getAPI($this->module_info->module, 'api');
                    if(method_exists($oAPI, $this->act)) {
                        $oAPI->{$this->act}($this);
                    }
                }
            }else if($this->module_info->module_type == 'controller'){
                if(Context::getResponseMethod() == 'JSON'){

                }

            }

            return true;
        }
    }
?>

ResponseMethod가 JSON이나 XML이고 module.xml에 view type으로 정의 되어 있을 경우 act의 함수는 모듈명.api.php에 정의가 가능합니다.

무엇보다 훌륭한것은...response 입니다.
json형식으로 온다는 것 입니다.
사용자 삽입 이미지






2008년 6월 17일 화요일

perl JSON module 사용 from_json으로 파싱된 데이터 사용

# $str_json에는 json형식의 string 데이터가 들어간다.
# orderingConfirmList의 key에 array의 형식으로 데이터가 들어있음[{"ORDER_NO":"11"},{"ORDER_NO":"2"}] 모 이쯤 되겠지.
# 그라지~~~

my $_scalar = from_json( $_str_json );
my @values = @{$_scalar->{'orderingConfirmList'}};

foreach my $_v ( @values )
{
        # print Dumper ( $_v );
        print $_v->{ORD_NO}. "\n";
}

2008년 4월 7일 월요일

Json encode ..

json string을 json object로 반드는 케이스
jsonData = Ext.util.JSON.decode("{'total_rows':4,'list':[{'trans_date_pos':'2008-4-4','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-4','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-4','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-4','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-5','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-5','domain':'test','warehouse':'K','qty':13},{'trans_date_pos':'2008-4-5','domain':'test','warehouse':'K','qty':13}]}");
 
생성된 json object를 store에 저장함
// ext.data.groupingstore는 해당 자료를 grouping하기 위해 store대신 사용함
    store = new Ext.data.GroupingStore({       
        reader: new Ext.data.JsonReader({
            totalProperty: 'total_rows',
            root: "list",
            fields: ["trans_date_pos","domain","warehouse","qty"]
        }),
        data: jsonData,
        groupField:'trans_date_pos',
        autoLoad: true
    });


2008년 4월 3일 목요일

array concat 를 사용하다...array를 결합

<script type="text/javascript">

var arr = new Array(3);
arr[0] = "Jani";
arr[1] = "Tove";
arr[2] = "Hege";

var arr2 = new Array(3);
arr2[0] = "John";
arr2[1] = "Andy";
arr2[2] = "Wendy";

document.write(arr.concat(arr2));

</script>

json에서 사용한다면
var objJson = new object();
objJson.list = [1,2,3,4];

라고 하면 아래와 같은 구조로 만들어 질 것 같다.
objJson = { list:[1,2,3] } 이라고 가정하고

objJson.list.concat( arr2 ) 정도이면 될까?

여러개의 언어를 동시에 사용하다 보니..헛갈리네. 나참 다들 비슷해서리..

Json사용을 위한 셋팅2

pear에서 json관련 라이브러리를 설치 하면
json_encode와 json_decode를 아무데서나 call할 수 있는 환경이 된다.
하..지..만 설치가 되지 않는 경우도 있다.


<?php
if ( !function_exists('json_decode'
) ){
    function
json_decode($content, $assoc=false
){
                require_once
'Services/JSON.php'
;
                if (
$assoc
){
                   
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE
);
        } else {
                   
$json = new Services_JSON
;
                }
        return
$json->decode($content
);
    }
}

if ( !
function_exists('json_encode'
) ){
    function
json_encode($content
){
                require_once
'Services/JSON.php'
;
               
$json = new Services_JSON
;
               
        return
$json->encode($content
);
    }
}
?>
참조 사이트: http://pear.php.net/pepr/pepr-proposal-show.php?id=198


[json] Json 방식으로 Ajax request

먼저 json방식의 자료를 만들어야겠다.

array일 경우
var Beatles = ["Paul","John","George","Ringo"];
var Beatles = new Array("Paul","John","George","Ringo");

Object일 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll"
}

아래의 경우는 위와 동일함
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";

Object 출력
alert(Beatles.Style); //Dot Notation
alert(Beatles["Style"]); //Bracket Notation


Array를 Object에 사용할 경우
var Beatles = {
     "Country" : "England",
     "YearFormed" : 1959,
     "Style" : "Rock'n'Roll",
     "Members" : ["Paul","John","George","Ringo"]
}


Array내부에 Object사용
var Rockbands = [
     {
         "Name" : "Beatles",
         "Country" : "England",
         "YearFormed" : 1959,
         "Style" : "Rock'n'Roll",
         "Members" : ["Paul","John","George","Ringo"]
     }
,
    {
        "Name" : "Rolling Stones",
        "Country" : "England",
        "YearFormed" : 1962,
        "Style" : "Rock'n'Roll",
         "Members" : ["Mick","Keith","Charlie","Bill"]
      }

]

Json Syntax
Javascript Object 와 흡사함

{
"Name" : "Beatles",
"Country" : "England",
"YearFormed" : 1959,
"Style" : "Rock'n'Roll",
"Members" : ["Paul","John","George","Ringo"]
}

내가 원하는것은 만들어진 Json을 어떻게 Ajax를 사용해 전송 할 것인가? 하는 것이다.
그 전에 Json Parser란게 필요하다.
사실 eval( ) 을 사용해서 parsing을 하고 있었는데 parser를 쓰면 더 좋단다. 흠흠..

http://www.json.org/json.js

  • JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
  • JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.
  • 순서는 다음과 같다.
    Client Side
    1. Json을 만든다.
    2. Json파서를 사용해 stringify() 작업을 한다. 이건 object를 string으로 만들어 버리겠다는것?
    3. Send the URL-encoded JSON string to the server as part of the HTTP Request

    Sample:

    var objJSON = {
       "msg" : MSG
      };
      var strJSON = encodeURIComponent(JSON.stringify(objJSON));
      new Ajax.Request("ReceiveJSON.jsp",
       {
        method: "post",
        parameters: "strJSON=" + strJSON,
        onComplete: Respond
       });


    Server Side(php)
    strJSON 파라미터를 받아서 json_decode() 하게 되면 array의 형식으로 변경됨.
    알아서 작업하면 됨....

    -------------------------
    헌데 분명
    Content_Type     => 'application/json',
    Content              => $json_req,
    의 방법을 이용한 경우가 있는데 이럴때는 서버측에서 어떻게 해야 하나?





     



    2007년 10월 26일 금요일

    [php-json] 설치

    다운 받았지..
    http://aurore.net/projects/php-json/


    앞축을 풀어야 함
    root계정으로 들어가서 냅다 압축을 풀었음
    # tar -jxvf php-json-ext-1.2.1.tar.bz2

    쓰여진 대로 설치함
    ./configure
    make
    make install


    * configure시 php-config가 없다고 하는 경우가 있다.

    ./configure --with-php-config=/usr/local/php/bin/php-config


    extension=json.so 를 php.ini / php.d에 설정해주라고 하는데 어떻게 하는거지?

    간단한 예제 작성
    <?
    $val = array("abc" => 12,
                 "foo" => "bar",
                 "bool0" => false,
                 "bool1" => true,
                 "arr" => array(1, 2, 3, null, 5),
                 "float" => 1.2345
                );
    $output = json_encode($val);
    echo $output."\n";

    ?>
    ~            

    작동 안됨
    Unable to load dynamic library './json.so'

    json.so 를 /usr/local/lib 로 가져다 넣음
    php.ini에
    ; Directory in which the loadable extensions (modules) reside.
    extension_dir = "./"
    extension_dir = "/usr/local/php/lib/php/extensions"

    extension=json.so 를 셋팅 해 줌

    오에~
    dk
    결과:
    php json.php
    {"abc":12,"foo":"bar","bool0":false,"bool1":true,"arr":[1,2,3,null,5],"float":1.2345}

    [JSON] Javascript Object Notation

    // 데이터 공유를 위한 간단한 표현방식 정도라고 얘기 할 수 있다.
    var myJSONObject = {"bindings": [
            {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
            {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
            {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
        ]
    };

    // Members can be retrieved using dot or subscript operators.
     myJSONObject.bindings[0].method    // "newURI"
     

    // JSON text를 object롤 변경하기 위해서는 eval() function을 사용해야 한다.
    // 보통 ajax에서 json으로 return받으면 eval을 사용해 object에 입력해야 함
    var myObject = eval('(' + myJSONtext + ')');

    2007년 8월 27일 월요일

    json사용을 위한 PECL extensions설치

    php같은 경우 module을 여러 관리 프로그램으로 install하네..희안하네~

    # pecl install json
    WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update
    downloading json-1.2.1.tgz ...
    Starting to download json-1.2.1.tgz (17,780 bytes)
    ......done: 17,780 bytes
    11 source files, building
    running: phpize
    Configuring for:
    PHP Api Version:         20041225
    Zend Module Api No:      20050922
    Zend Extension Api No:   220051025