메뉴 건너뛰기

조회 수 10323 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

JavaScript에서 json을 생성 하는 방식입니다.

* JavaScript 에서 JSON Parse 하시려는 분은 여기 참고 => http://huskdoll.tistory.com/49

* JAVA 에서 JSON 생성 하시려는 분은 여기 참고 => http://huskdoll.tistory.com/38

* JAVA에서 JSONParser 사용 하시려는 분은 여기 참고 => http://huskdoll.tistory.com/6

json은 key : value 방식 으로 되어 있는데요. value 안에 다시 json 형식의 데이터를 넣어 봤습니다.

말로 설명하기 좀 어려운데 아래 소스를 실행해 보시기 바랍니다

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
      <title>Home</title>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
      <script>
       
      $(function() {
         
        $("#checkJson").click(function() {
           
          //사람 정보
          var personArray = new Array();
             
          var personInfo = new Object();
           
          personInfo.name = "송강호";
          personInfo.age = "25";
          personInfo.gender = "남자";
          personInfo.nickname = "남궁민수";
             
          personArray.push(personInfo);
           
           
          personInfo = new Object();
           
          personInfo.name = "전지현";
          personInfo.age = "21";
          personInfo.gender = "여자";
          personInfo.nickname = "예니콜";
           
          personArray.push(personInfo);
           
          //책 정보
          var bookArray = new Array();
           
          bookInfo = new Object();
           
          bookInfo.name = "사람은 무엇으로 사는가?";
          bookInfo.writer = "톨스토이";
          bookInfo.price = "100";
          bookInfo.genre = "소설";
          bookInfo.publisher = "톨스토이 출판사";
           
          bookArray.push(bookInfo);
           
           
          bookInfo = new Object();
           
          bookInfo.name = "홍길동전";
          bookInfo.writer = "허균";
          bookInfo.price = "300";
          bookInfo.genre = "소설";
          bookInfo.publisher = "허균 출판사";
           
          bookArray.push(bookInfo);
           
           
          bookInfo = new Object();
           
          bookInfo.name = "레미제라블";
          bookInfo.writer = "빅토르 위고";
          bookInfo.price = "900";
          bookInfo.genre = "소설";
          bookInfo.publisher = "빅토르 위고 출판사";
           
          bookArray.push(bookInfo);
           
          //사람, 책 정보를 넣음
          var totalInfo = new Object();
           
          totalInfo.persons = personArray;
          totalInfo.books = bookArray;
           
          var jsonInfo = JSON.stringify(totalInfo);
          console.log(jsonInfo); //브라우저 f12개발자 모드에서 confole로 확인 가능
          alert(jsonInfo);
     
        });
         
      });
       
      </script>
    </head>
    <body>
        <br>
        <br>
        <a id="checkJson" style="cursor:pointer">확인</a>
    </body>
</html>

이런 형식이 됩니다.
{
    "persons":[
                        {"name":"송강호","age":"25","gender":"남자","nickname":"남궁민수"},
                        {"name":"전지현","age":"21","gender":"여자","nickname":"예니콜"}
                     ],
 
 
    "books":[
                     {"name":"사람은 무엇으로 사는가?","writer":"톨스토이","price":"100","genre":"소설","publisher":"톨스토이 출판사"},
                     {"name":"홍길동전","writer":"허균","price":"300","genre":"소설","publisher":"허균 출판사"},
                     {"name":"레미제라블","writer":"빅토르 위고","price":"900","genre":"소설","publisher":"빅토르 위고 출판사"}
                 ]
}

완성된 JSON 데이터는 여기에서 (http://jsonlint.com/) 검증 및 정렬 해보시면 됩니다.


* 여기 아래부터는 제가 프로젝트에서 사용한 소스의 일부분 인데 나중에 다시 보기 위해 적었습니다.

위와 동일한 방식이지만 데이터 넣는 부분을 HashMap 처리 해 보았습니다.

간단한 방식은 위에 소스를 참고 해주세요.

일단 JavaScript에서 HashMap 처럼 사용하기 위해 함수를 하나 생성 하자요. (JSON 부분만 보실분은 확인 안하셔도 됩니다.)


HashMap = function(){   
     this.map = new Array(); 
 };   
 HashMap.prototype = {   
     put : function(key, value){   
         this.map[key] = value; 
     },   
     get : function(key){   
         return this.map[key]; 
     },   
     getAll : function(){   
         return this.map; 
     },   
     clear : function(){   
         this.map = new Array(); 
     },   
     isEmpty : function(){     
          return (this.map.size() == 0); 
     }, 
     remove : function(key){     
          delete this.map[key]; 
     }, 
     toString : function(){ 
         var temp = ''; 
         for(i in this.map){   
             temp = temp + ',' + i + ':' +  this.map[i]; 
         } 
         temp = temp.replace(',',''); 
           return temp; 
     }, 
     keySet : function(){   
        var keys = new Array();   
         for(i in this.map){   
             keys.push(i); 
         }   
         return keys; 
    } 
 }; 


HashMap에 값을 넣습니다


var channelInfoMap = new HashMap();
channelInfoMap.put(keyChannelId, channelImgType+"`"+channelType+"`"+channelTypeSeq);
var connectionConfMap = new HashMap();
connectionConfMap.put(conn[i].id, cStatus+"`"+cDay+"`"+cHour);


그리고 생성한 HashMap를 가져와 데이터를 추출 하고 JSON 형식으로 만듭니다.


var channelInfoConf = channelInfoMap.getAll(); 
 
      
//채널 정보를 JSON 형식으로 생성
var channelArrayArg = new Array();
 
for(i in channelInfoConf){
  var jsonArg = new Object();
  jsonArg.name = i;
  jsonArg.type = channelInfoMap.get(i).split("`")[0];
  jsonArg.channelType = channelInfoMap.get(i).split("`")[1];
  jsonArg.channelTypeSeq = channelInfoMap.get(i).split("`")[2];
  
  channelArrayArg.push(jsonArg);
  
}
 
//커넥션 정보를 JSON 형식으로 생성
var connectionArrayArg = new Array();
var connectionVal = connectionMap.getAll();
 
for(i in connectionVal){
  var jsonArg = new Object();
  jsonArg.name = i;
  jsonArg.from = connectionMap.get(i).split("`")[0];
  jsonArg.to = connectionMap.get(i).split("`")[1];
  
  jsonArg.status = connectionConfMap.get(i).split("`")[0];
  jsonArg.day = connectionConfMap.get(i).split("`")[1];
  jsonArg.hour = connectionConfMap.get(i).split("`")[2];
  
  connectionArrayArg.push(jsonArg);
  
}
 
var totalAutoPlanInfo = new Object();
         
totalAutoPlanInfo.channelInfo = channelArrayArg;
totalAutoPlanInfo.connectionInfo = connectionArrayArg;
 
alert(JSON.stringify(totalAutoPlanInfo));
 
/* 아래와 같이 만들어 진다. 값은 뭐.... 넣은대로
{
"channelInfo":
[
    {"name":"channelWindow2","type":"M","channelType":"10","channelTypeSeq":"1"},                       
    {"name":"channelWindow3","type":"P","channelType":"07","channelTypeSeq":"1"}
],
 
"connectionInfo":
[
    {"name":"con_31","from":"channelWindow1","to":"channelWindow2","status":"s","day":"1","hour":"1"},
    {"name":"con_39","from":"channelWindow2","to":"channelWindow3","status":"s","day":"2","hour":"2"}
]
}
*/



  1. 엔코딩/디코딩 함수

    Date2016.09.21 Views6033
    Read More
  2. 간단한 동적 SELECT 박스 구현하기

    Date2016.10.06 Views12368
    Read More
  3. 브라우저별 이미지 크기 변경

    Date2016.11.17 Views7928
    Read More
  4. JavaScript 에서 JSON 생성

    Date2016.11.17 Views10323
    Read More
  5. input type file multiple list (파일 업로드 리스트 확인)

    Date2016.11.17 Views12437
    Read More
  6. javascript 화면 캡쳐

    Date2016.11.17 Views9821
    Read More
  7. 접근성 윈도우 팝업 띄우기

    Date2016.12.22 Views7114
    Read More
  8. 도메인 체크

    Date2016.12.22 Views5928
    Read More
  9. setTimeout 대체 스크립트 함수 (일시멈춤)

    Date2016.12.22 Views6241
    Read More
  10. GET방식으로 전송시 특수문자함께 전송하는 방법

    Date2016.12.22 Views12346
    Read More
  11. 복사방지+드래그금지+마우스우클릭 금지

    Date2016.12.22 Views7912
    Read More
  12. response.setHeader

    Date2016.12.22 Views7358
    Read More
  13. 자바스크립트 변수,함수,객체의 표현

    Date2016.12.22 Views5369
    Read More
  14. 자바스크립트 실행 시간 측정

    Date2016.12.22 Views8930
    Read More
  15. 자바스크립트 및 CSS를 이용한 숫자만 입력받기

    Date2016.12.22 Views6321
    Read More
  16. 자바스크립트 모음

    Date2016.12.22 Views5778
    Read More
  17. [단축키 설정 자바스크립트]shortcut.js

    Date2016.12.22 Views8375
    Read More
  18. setTimeout() / clearTimeout() / setInterval()

    Date2016.12.22 Views8162
    Read More
  19. 우클릭 금지

    Date2016.12.23 Views5701
    Read More
  20. 이전, 위로 이동

    Date2016.12.23 Views5740
    Read More
Board Pagination Prev 1 ... 3 4 5 6 7 8 9 10 11 12 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved