관리 메뉴

SIMPLE & UNIQUE

JSON 데이터 삽입 방식 본문

Java & Spring/Solution

JSON 데이터 삽입 방식

착한코딩 2017. 3. 27. 18:19

JSON(JavaScript Object Notation)

  •  JSON 다른 언어간에 객체를 전달하는 포맷으로 많이 사용된다
  •  자바스크립트를 위한 것이고 객체 형식으로 자료를 표현하는 데이터 포맷
  • 주로 AJAX를 사용해 데이터를 주고 받을 때 그 데이터 포맷으로 JSON을 사용하는 것이다.

$.ajax({

    url: "drug.jsp",

    type: "POST",

    cache:false,

    timeout : 30000, 

    dataType:"json",

    data: {

            "location": "서울",

            "date": 6,

            "booking": false

},

    success: function(data) {

        alert('success');

    },

});


  • 아래와 같이 직접 key : value 로 입력하거나

       data: 

{

            "location": "서울",

            "date": 6,

            "booking": false

},



  • 원하는 형태로 String으로 만들어서 Json으로 파싱해 사용한다.


           var jsonString = "";

  jsonString += "{";

  jsonString += " \"" + "location" + "\" : " + "\"" + "서울" + "\",";                      // => "location": "서울",

  jsonString += " \"" + "date" + "\" : " + "\"" + "6" + "\",";

  jsonString += " \"" + "booking" + "\" : " + "\"" + "false" + "\"";

   jsonString += "}";


  var jsontest = j$.parseJSON(jsonString);

           data: jsontest 


**JSON.parse : JSON text를 Javascript object로 바꾼다.


  • 스크립트 배열을  JSON 문자열로 변환하여 사용한다.


var testList = new Array() ;

          

        for(var i=1; i<=2; i++){

            var data = new Object() ;

            data.number = i ;

            data.name = "Tester #" + i ;

            testList.push(data) ;

        }

        

  var jsonData = JSON.stringify(testList) ;


**JSON.stringify : Javascript object를 JSON text로 바꾼다. 그리고 String형으로 저장한다.



  • parse 는 string 개체를 json 개체로,  stringify 는 json 개체를 string 개체로 변환시켜준다.

var Data = {

            "location": "서울",

            "date": 6,

}


var Person = JSON.stringify(Data);

var Person2 = JSON.parse(Person);


alert(Person);

/* Output: "{"location":"서울","date":"6"}" */

alert(Person2.location);

/* Output: "서울" */

alert(Person2);

/* Output: "[object Object]" */





down voteaccepted

When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example: [{"name":"item 1"},{"name": "item2} ]

On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example: {"name": "item1", "description":"a JSON object"}

Of course, JSON arrays and objects may be nested inside one another. One common example of this is an API which returns a JSON object containing some metadata alongside an array of the items matching your query:

{"startIndex": 0, "data": [{"name":"item 1"},{"name": "item2"} ]}

출처 : http://stackoverflow.com/questions/12289844/difference-between-jsonobject-and-jsonarray






Comments