메뉴 건너뛰기

조회 수 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. 자바스크립트 아이디 기억하기 기능 구현 (쿠키저장)

    Date2015.06.19 Views10924
    Read More
  2. 이벤트 - 페이지 로드 후 이벤트 처리하기 ( window.onload )

    Date2015.06.19 Views10871
    Read More
  3. 'button', 클릭한 횟수 알아내기!

    Date2015.02.03 Views10757
    Read More
  4. 핸드폰 번호 일부 마스킹크 작업 (정규식 이용)

    Date2015.06.19 Views10741
    Read More
  5. 5초 후에 해당페이지로 url 옮기기

    Date2014.02.27 Views10485
    Read More
  6. JavaScript 에서 JSON 생성

    Date2016.11.17 Views10323
    Read More
  7. 자바 스크립트 confirm()함수에서 (확인,취소) -> (예,아니오)

    Date2014.03.01 Views10213
    Read More
  8. 자바스크립트 영문입력, 숫자만입력, 한글만 입력, 붙여넣기 방지

    Date2015.02.02 Views10179
    Read More
  9. 예제 - 자바스크립트로 현재 달의 달력 만들기 (calendar)

    Date2015.06.19 Views10063
    Read More
  10. Javascript selectbox selected 컨트롤

    Date2018.06.21 Views10056
    Read More
  11. javascript 화면 캡쳐

    Date2016.11.17 Views9821
    Read More
  12. 'onmouseover', 마우스 오버 효과 - 글씨 바꾸기!

    Date2015.02.03 Views9436
    Read More
  13. location.href 로 새창 여는 방법 (target=_blank 효과)

    Date2015.06.19 Views9404
    Read More
  14. 이미지 마우스 드래그로 스크롤을 움직이는 소스

    Date2014.03.17 Views9362
    Read More
  15. 자바스크립트 API 문서

    Date2015.06.19 Views9086
    Read More
  16. 5초후 자동으로 창닫기

    Date2015.02.03 Views9034
    Read More
  17. 자바스크립트 실행 시간 측정

    Date2016.12.22 Views8930
    Read More
  18. 주민등록번호로 성별/나이/연령대 구분

    Date2014.03.01 Views8794
    Read More
  19. 특정부위 마우스 오버시 설명을 보여주는 소스

    Date2014.03.17 Views8697
    Read More
  20. 마우스 드래그, 오른쪽 팝업메뉴, 선택 막기 (IE11, 파이어폭스, 크롬 확인)

    Date2015.06.19 Views8577
    Read More
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved