본문 바로가기
✨ Front-end/자바스크립트(JS)

[JavaScript] JSON 객체, 배열 사용법

by 환풍 2023. 9. 1.
728x90
반응형

 

 

JSON 객체

 

See the Pen Untitled by ParkJooHong (@ParkJooHong) on CodePen.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON(객체)</title>
<script>
function init(){
    var emp={"name":"홍길동"
            "age":25
            "phone":"010-1111-111"
            "addr":"서울"};
    //alert(emp['name']);   //or emp.name  
    
    var msg="";
    msg +="이름:" + emp.name
        + "<br>나이:" +emp.age
        + "<br>연락처:" + emp['phone'
        + "<br>주소:" + emp['addr']+"<br>";
    
    document.getElementById("result").innerHTML=msg;
}
</script>
</head>
<body onload="init()">
<h2>JSON 표기법</h2>
<div id="result"></div>
</body>
</html>
cs

 

JSON 배열

See the Pen Untitled by ParkJooHong (@ParkJooHong) on CodePen.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script>
        var emp = {
            "id""abcd",
            "pw""1234",
            "name""홍길동",
            "point"1250
        };
 
        function login() {
            var sid = document.getElementById("id").value;
            var spw = document.getElementById("pw").value;
 
            if (sid == "" || spw == "") {
                document.getElementById("confirm").innerHTML = "id와 pw를 입력하시오";
            } else {
                if (emp.id == sid && emp.pw == spw)
                    document.getElementById("confirm").innerHTML
                        = "<span style='color:green'>"
                        + emp.name + "님 환영합니다.<br>현재 포인트는 "
                        + emp.point + "점 입니다.</span>";
                else
                    document.getElementById("confirm").innerHTML
                        = "<span style='color:red'>아이디 또는 비밀번호가 틀립니다.</span>";
            }
 
        }
    </script>
</head>
 
<body>
    <label for="input">[로그인 화면]</label><br><br>
    <input type="text" id="id"><span>아이디를 입력하시오</span><br>
    <input type="text" id="pw"><span>비밀번호를 입력하시오</span><br>
    <button id="log" onclick="login()">Login</button><br><br>
    <span id="confirm"></span>
</body>
 
</html>
cs

 

JSON(stingify, parse)

See the Pen Untitled by ParkJooHong (@ParkJooHong) on CodePen.

 

1
2
3
4
5
6
7
8
9
10
11
user = {
    name"admin",
    email: "aa@bb.com",
    phone: "010-1111-1111"
  };
 
  userStr = JSON.stringify(user);
 
  JSON.parse(userStr, function (key, value) {
    alert(key + "  " + value);
  });
cs

 

stringify( ) 

JSON 객체를 string으로 변환해 준다.

 

parse( )

string 객체를 JSON객체로 변환해 준다.

728x90
반응형

댓글