반응형

MySQL(MariaDB)과 구글 차트를 연동해 보자.

 

아래 내용을 참고해 웹서버와 데이터베이스를 준비한다.

2021.08.25 - [Linux] - Linux(Ubuntu) Build Your Own Web Server - 리눅스(우분투)로 웹서버 만들기

2021.08.28 - [Linux] - Linux(Ubuntu) MariaDB(MySQL) Server Remote Access - 데이터베이스 원격 접속

(데이터베이스는 로컬로 사용하므로 원격 설정을 할 필요는 없다)

 

위와 같은 데이터베이스와 테이블을 생성한다.

 

시간, 온도, 습도 데이터를 적당히 입력한다.

 

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!--
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    -->
 
    <?php
        // 에러가 발생하면 내용 표시
        error_reporting(E_ALL);
        ini_set('display_errors''1');
 
        $mysql_host = "localhost";
        $mysql_user = "root";
        $mysql_password = "1234";
        $mysql_db = "test_db";
 
        $conn = mysqli_connect($mysql_host$mysql_user$mysql_password$mysql_db);
        if (!$conn) {
            die("Database Connect Error: " . mysqli_connect_error());
        }
            
        //echo "Database Connected.<br><br>";
            
        $sql = "SELECT * FROM test_tb";
        $result = mysqli_query($conn$sql);
        
        if (mysqli_num_rows($result> 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data_array[] = $row;
            }
            $chart = json_encode($data_array);
        } else {
            echo "No Data";
        }
        
        //echo $chart;
 
        mysqli_close($conn);
    ?>
 
    <script type="text/javascript">
        google.charts.load('current', { packages: ['corechart''line'] });
        google.charts.setOnLoadCallback(drawChart);
        
        function drawChart() {
            var chart_array = <?php echo $chart; ?>;
            //console.log(JSON.stringify(chart_array))
            var header = ['dt''temp''humid'];
            var row = "";
            var rows = new Array();
            jQuery.each(chart_array, function(index, item) {
                row = [
                    item.dt,
                    Number(item.temp),
                    Number(item.humid)
                ];
                rows.push(row); 
            });
 
            var jsonData = [header].concat(rows);
            var data = new google.visualization.arrayToDataTable(jsonData);
            var options = {
                title: 'Temperaure & Humid',
                hAxis: {
                    title: 'Time'
                },
                series: {
                    0: { targetAxisIndex: 0 },
                    1: { targetAxisIndex: 1 }
                },
                vAxes: {
                    0: {
                        title: 'Temperature',
                        viewWindow: { min: -30, max: 50 }
                    },
                    1: {
                        title: 'Humid',
                        viewWindow: { min: 30, max: 100 }
                    }
                }
                //,
                //curveType: 'function',
                //legend: { position: 'bottom' }
            };
 
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id="chart_div" style="width: 900px; height: 500px"></div>
</body>
</html>
 

 

소스를 입력하고 웹서버에 저장한다.(/var/www/html/index.php)

 

웹서버에 접속하면 위와 같은 그래프가 표시된다.

 

 

X축 레이블을 좀 더 보기 편하게 바꾸고 테이블 차트도 추가해 보자.

 

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <!--
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    -->
 
    <?php
        // 에러가 발생하면 내용 표시
        error_reporting(E_ALL);
        ini_set('display_errors''1');
 
        $mysql_host = "localhost";
        $mysql_user = "root";
        $mysql_password = "1234";
        $mysql_db = "test_db";
 
        $conn = mysqli_connect($mysql_host$mysql_user$mysql_password$mysql_db);
        if (!$conn) {
            die("Database Connect Error: " . mysqli_connect_error());
        }
            
        //echo "Database Connected.<br><br>";
            
        $sql = "SELECT * FROM test_tb";
        $result = mysqli_query($conn$sql);
        
        if (mysqli_num_rows($result> 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data_array[] = $row;
            }
            $chart = json_encode($data_array);
        } else {
            echo "No Data";
        }
        
        //echo $chart;
 
        mysqli_close($conn);
    ?>
 
    <script type="text/javascript">
        google.charts.load('current', { packages: ['corechart''line'] });
        google.charts.load('current', { packages: ['table'] });
        google.charts.setOnLoadCallback(drawChart);
        
        function drawChart() {
            var chart_array = <?php echo $chart; ?>;
            //console.log(JSON.stringify(chart_array))
            var header = ['Date&Time(MM-DD HH:MM)''Temp''Humid'];
            var row = "";
            var rows = new Array();
            jQuery.each(chart_array, function(index, item) {
                row = [
                    item.dt.substr(511),  // 너무 긴 날짜 및 시간을 짧게 추출
                    Number(item.temp),
                    Number(item.humid)
                ];
                rows.push(row); 
            });
 
            var jsonData = [header].concat(rows);
            var data = new google.visualization.arrayToDataTable(jsonData);
 
            var lineChartOptions = {
                title: 'Temperaure & Humid',
                hAxis: {
                    title: 'Time',
                    showTextEvery: 4    // X축 레이블이 너무 많아 보기 힘드므로 4개마다 하나씩 표시
                },
                series: {
                    0: { targetAxisIndex: 0 },
                    1: { targetAxisIndex: 1 }
                },
                vAxes: {
                    0: {
                        title: 'Temperature',
                        viewWindow: { min: -30, max: 50 }
                    },
                    1: {
                        title: 'Humid',
                        viewWindow: { min: 30, max: 100 }
                    }
                }
                //,
                //curveType: 'function',
                //legend: { position: 'bottom' }
            };
 
            var lineChart = new google.visualization.LineChart(document.getElementById('lineChart_div'));
            lineChart.draw(data, lineChartOptions);
 
            // 테이블 차트
            var tableChartOptions = {
                showRowNumber: true,
                width: '40%',
                height: '20%'
            }
 
            var tableChart = new google.visualization.Table(document.getElementById('tableChart_div'));
            tableChart.draw(data, tableChartOptions);
        }
    </script>
</head>
<body>
    <div id="lineChart_div" style="width: 900px; height: 500px"></div>
    <div id="tableChart_div"></div>
</body>
</html>
 

 

소스를 수정하고 웹서버에 저장한다.(/var/www/html/index.php)

 

웹서버에 접속하면 위와 같은 그래프와 차트가 표시된다.

 

※ 참고

2022.05.05 - [Web Development] - Google Chart - 구글 차트 1

반응형
Posted by J-sean
:
반응형

C#으로 JSON 데이터를 파싱하고 원하는 값을 찾아보자.

 

아래와 같은 JSON 데이터 파일을 준비한다.

 

data.json
0.00MB

 

Newtonsoft.Json을 설치한다.

 

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.IO;
 
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonData = File.ReadAllText(@"d:\data.json");
            //Console.WriteLine(jsonData);
 
            JObject jObject = JObject.Parse(jsonData);
            //Console.WriteLine(jObject.ToString());
 
            Console.WriteLine("Last Update: " + (jObject["LastUpdate"]));
            Console.WriteLine("SalesRecord Count: " + (jObject["SalesRecord"]).Count());
            Console.WriteLine("SalesRecord[2]\"total\": " + jObject["SalesRecord"][2]["total"]);
 
            JToken jToken = jObject["SalesRecord"];
            foreach (JToken data in jToken)
            {
                Console.WriteLine("■ " + data["date"+ ": " + data["item"]);
            }
 
            Item item = JsonConvert.DeserializeObject<Item>(jsonData);
            Console.WriteLine("Last Update: " + item.LastUpdate);
            foreach (Record record in item.SalesRecord)
            {
                Console.WriteLine("■ " + record.date + ": " + record.item);
            }
 
            string serializedJsonData = JsonConvert.SerializeObject(item);
            //Console.WriteLine(serializedJsonData);
            JObject serializedJObject = JObject.Parse(jsonData);
            //Console.WriteLine(serializedJObject);
        }
 
        // 모든 필드명이 json 데이터의 key와 일치해야 한다.
        class Item
        {
            public string LastUpdate;
            public List<Record> SalesRecord;
        }
 
        class Record
        {
            public string date;
            public string item;
            public int price;
            public int quantity;
            public int total;
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

JSON 데이터가 원하는대로 출력된다.

 

반응형
Posted by J-sean
:
반응형

웹서버로 만든 웹페이지에서 JSON 데이터를 분석하고 테이블이나 리스트등 원하는 형식으로 보여 줄 수 있다.


2019/10/08 - [Linux] - Build your own web server with Fedora linux - 페도라 리눅스로 간단한 웹서버 만들기


웹페이지에 보여 줄 데이터를 준비한다.


데이터를 JSON 형식으로 변환 한다. 아래 링크에서 간단히 변환 할 수 있다.

https://shancarter.github.io/mr-data-converter/


변환된 데이터는 data.json 파일로 저장 한다.


html/data 디렉토리를 만들고 data.json 파일을 저장 한다.



아래 파일과 같은 내용으로 index.php를 만들고 html 디렉토리에 저장 한다.


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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
    $file_contents = file_get_contents('./data/data.json');
    $data = json_decode($file_contents, true);
?>
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP JSON parser sample</title>
    </head>
   
    <body>
    <table border="1" bordercolor="blue">
 
    <tr bgcolor="yellow">
    <th> 날짜 </th>
    <th> 아이템 </th>
    <th> 가격 </th>
    <th> 수량 </th>
    <th> 합계 </th>
    </tr>
 
    <?php foreach ($data as $row) { ?>
        <tr align="center">
 
        <td> <?php print $row['date']; ?> </td>
        
        <td> <?php print $row['item']; ?> </td>
        
        <td> <?php print $row['price']; ?> </td>
        
        <td> <?php print $row['quantity']; ?> </td>
        
        <td> <?php print $row['total']; ?> </td>
 
        </tr>
        
    <?php } ?>
 
    </table>
 
 
    <?php
    foreach ($data as $row) {
        print $row['date'];
        print ' , ';
        print $row['item'];
        print ' , ';
        print $row['price'];
        print ' , ';
        print $row['quantity'];
        print ' , ';
        print $row['total'];
        print '<br />';
    }
    ?>
 
 
    <?php
    foreach ($data as $row) {
        printf("<li>%s %s %s %s %s</li>\n", $row['date'], $row['item'], $row['price'], $row['quantity'], $row['total']);
    }
    ?>
    
    </body>
 
</html>



서버에 접속하면 data.json의 내용이 index.php에 설정한대로 표시된다.


반응형
Posted by J-sean
:
반응형

웹서버에 데이터를 요청하고 app에서 응답 받아 처리할 수 있다.


서버에서 전달 되는 데이터 형식(Json)

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "LastUpdate":"2019.10.12",
    "SalesRecord":
    [
        {"date":"2016.03.08","item":"apple","price":2400,"quantity":84,"total":201600},
        {"date":"2016.07.29","item":"grape","price":3100,"quantity":37,"total":114700},
        {"date":"2017.10.25","item":"peach","price":4600,"quantity":55,"total":253000},
        {"date":"2018.12.08","item":"banana","price":1500,"quantity":83,"total":124500},
        {"date":"2019.05.09","item":"melon","price":7200,"quantity":75,"total":540000},
        {"date":"2019.10.17","item":"coconut","price":6800,"quantity":59,"total":401200},
        {"date":"2019.11.07","item":"strawberry","price":4900,"quantity":30,"total":147000}
    ]
}



<AndroidManifest.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:usesCleartextTraffic="true">
        <!--
        android:usesCleartextTraffic
        Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP.
        The default value for apps that target API level 27 or lower is "true". Apps that target
        API level 28 or higher default to "false". When the attribute is set to "false", platform
        components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse
        the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged
        to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of
        confidentiality, authenticity, and protections against tampering; a network attacker can
        eavesdrop on transmitted data and also modify it without being detected.
        -->



<MainActivity.java>

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    TextView textView;
 
    static RequestQueue requestQueue;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeRequest();
            }
        });
 
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }
 
    public void makeRequest() {
        String url = editText.getText().toString();
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //Server(Ubuntu) data encoding
                            response = new String(response.getBytes("iso-8859-1"), "utf-8");
                            //textView.append("Raw data: " + response);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
 
                        Gson gson = new Gson();
                        RequestResult requestResult = gson.fromJson(response, RequestResult.class);
                        textView.setText("Items count: " + requestResult.SalesRecord.size() + '\n');
                        textView.append("Last Update: " + requestResult.LastUpdate + '\n');
                        ArrayList<Data> items = requestResult.SalesRecord;
                        for (int i = 0; i < items.size(); i++) {
                            textView.append(String.format("■ Date: %s, Item: %s, Price: %s, Quantity: %s, Total: %s\n",
                                    items.get(i).date, items.get(i).item, items.get(i).price, items.get(i).quantity, items.get(i).total));
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        textView.append("Error: " + error.getMessage());
                    }
                }
        ) {
            @Override
            protected Map<StringString> getParams() throws AuthFailureError {
                Map<StringString> params = new HashMap<StringString>();
 
                return params;
            }
        };
 
        request.setShouldCache(false);
        requestQueue.add(request);
        textView.setText("Request sent.");
    }
}




<RequestResult.java>

1
2
3
4
public class RequestResult {
    String LastUpdate;
    ArrayList<Data> SalesRecord = new ArrayList<Data>();
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다.


<Data.java>

1
2
3
4
5
6
7
public class Data {
    String date;
    String item;
    String price;
    String quantity;
    String total;
}


서버 데이터의 key와 같은 이름의 변수를 만들어야 한다


실행 화면. 서버 주소를 입력하고 DATA REQUEST 버튼을 클릭한다.


서버부터 전달된 데이터가 지정한 대로 표시된다.


반응형
Posted by J-sean
:
반응형

Fedora Linux를 설치하고 간단히 웹서버를 만들 수 있다.

 

2021.08.25 - [Linux] - Linux(Ubuntu) Build Your Own Web Server - 리눅스(우분투)로 웹서버 만들기

 

Fedora 설치 중 Root 암호를 설정 한다. User Creation은 하지 않아도 된다.

 

Root 암호를 입력하고 설치를 완료 한다.

 

설치가 완료되면 재부팅하고 위에서 설정한 암호로 로그인 한다.

 

dnf -y install httpd 를 입력하고 Apache HTTP Server를 설치 한다.

 

 

 

Apache HTTP Server 설치가 완료되면 systemctl status httpd를 입력하고 상태를 확인한다. inactive 상태로 나타난다.

 

systemctl start httpd를 입력해 활성화 시키고 다시 systemctl status httpd를 입력해 확인 한다. active 상태로 나타난다.

 

systemctl enable httpd를 입력해 Apache HTTP Sever가 항상 작동 하도록 한다.

 

firewall-cmd --permanent --add-service=http

firewall-cmd --permanent --add-service=https

firewall-cmd --reload

위 명령어들로 방화벽에 http, https service를 등록한다.

 

ifconfig 명령어로 서버의 주소를 확인 한다. (192.168.11.131)

 

다른 컴퓨터로 서버 주소에 접속할 때 위와 같이 나오면 제대로 설정 된 것이다.

 

 

 

/var/www/html로 이동해서 index.html 파일을 생성 한다.

 

a나 i 키를 눌러 파일을 수정 한다.

 

간단한 html코드를 입력 하고 저장한다.

 

다시 다른 컴퓨터에서 서버에 접속했을 때 위와 같이 나오면 제대로 설정 된 것이다.

 

위와 같이 nmcli를 이용해 고정 IP 주소(192.168.11.200)를 정해 줄 수 있다.

 

※ -ipv4.addresses로 지정하면(앞에 -기호 추가) 원하는 주소를 삭제 할 수 있다고 하는데 처음 지정된 주소는 error가 발생 한다.

새로 추가한 주소는 error 없이 삭제 된다.

 

nmtui를 사용하자.

 

※ 설치: dnf install NetworkManager-tui

 

 

 

php를 설치 한다. 이번엔 -y 옵션을 주지 않았다.

 

y를 입력하고 설치를 진행 한다.

 

/var/www/html/index.php파일을 만든다. 파일명은 원하는대로 지정해도 된다.

 

서버에 설치된 php 정보를 보여주는 코드를 작성 하고 저장 한다.

 

httpd를 재시작 한다.

 

http://192.168.11.200/index.php 에 접속 했을때 위와 같은 화면이 나오면 제대로 설정된 것이다.

 

php-<extension>의 형식으로 필요한 PHP extension을 설치 한다.

 

※ 예를 들어 JSON 데이터를 다룬다면 아래와 같이 php-json을 설치 한다.

dnf install php-json

 

관련 업데이트가 함께 진행 된다.

 

반응형
Posted by J-sean
:

JSON 분석

Machine Learning 2019. 1. 18. 20:14 |
반응형

Python 기본 라이브러리 json을 이용해 JSON (JavaScript Object Notation) 형식을 분석할 수 있다.


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
45
import urllib.request as req
import os.path
import json
 
url = "https://api.github.com/repositories"
filename = "repositories.json"
 
if not os.path.exists(filename):
    #req.urlretrieve(url, filename)
    # Legacy interface. It might become deprecated at some point in the future.
    with req.urlopen(url) as contents:
        jsn = contents.read().decode("utf-8"# .decode("utf-8")이 없으면 jsn에는 str이 아닌 bytes가 저장 된다.
        # If the end of the file has been reached, read() will return an empty string ('').
        print(jsn)        
        # print(json.dumps(jsn, indent="\t")) 는 indent가 적용되어 출력되어야 하지만 원본이 indent가 적용되어 있지
        # 않아 indent 없이 출력 된다.
        with open(filename, mode="wt", encoding="utf-8") as f:
            f.write(jsn)
 
with open(filename, mode="rt", encoding="utf-8") as f:
    items = json.load(f) # JSON 문서를 갖고 있는 파일 포인터 전달. loads()는 JSON 형식의 문자열 전달
    for item in items:
        print("Name:", item["name"], "Login:", item["owner"]["login"])
 
test = {
    "Date" : "2019-01-17",
    "Time" : "21:30:24",
    "Location" : {
        "Town" : "Franklin",
        "City" : "Newyork",
        "Country" : "USA"
        }
    }
 
= json.dumps(test, indent="\t")
# Serialize obj to a JSON formatted str
# If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed
# with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects
# the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a
# string (such as "\t"), that string is used to indent each level.
print(s)
 
with open("dump.json", mode="wt") as f:
    json.dump(test, f, indent="\t")
# Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
cs


출력 결과 처음 부분.


출력 결과 마지막 부분.


write()으로 만든 repositories.json과 dump()으로 만든 dump.json 파일.



반응형
Posted by J-sean
:
반응형

JSON (JavaScript Object Notation)은 가벼운 data 교환 포멧이다. C++이 공식으로 지원하는 형식은 아니지만 분석에 사용 가능한 여러가지 라이브러리가 있다. 그 중 JsonCpp의 사용 방법이다.


홈페이지에서 소스를 다운 받고 압축을 풀면 아래와 같은 파일들이 나온다.


amalgamate.py를 실행한다.


dist라는 폴더에 소스파일과 헤더 파일이 생성된다.


makefiles - mscv2010 - jsoncpp.sln을 실행 한다.


Retarget Projects가 실행된다.


3개의 프로젝트가 나타난다.


각 프로젝트의 Property Pages - Configuration Properties - C/C++ - Code Generation - Runtime Library를 /MDd로 바꿔 준다.


Build 해 준다.


makefiles - msvc2010 - Debug 폴더에 lib_json.lib가 생성된다.


JsonCpp를 사용할 프로젝트를 만들고 Include Directory(jsoncpp-master\include)와 Library Directory(jsoncpp-master\makefiles\msvc2010\Debug)를 추가해 준다.




쓰기 예제

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
45
46
47
48
49
50
51
52
53
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ofstream json_file;
    json_file.open("JSON_DATA.json");
 
    Value Computer;
    Computer["CPU"= "I7";
    Computer["RAM"= "16G";
 
    Value Language;
    Language["C++"= "Visual Studio";
    Language["Python"= "IDLE";
    
    Computer["Program"= Language;
    Computer["HDD"= "2TB";
 
    Value Cable;
    Cable.append("Power");
    Cable.append("Printer");
    Cable.append("Mouse");
 
    Computer["Computer"]["Cable"= Cable;
 
    Value number;
    number["Int"= 123;
    number["Double"= 456.012;
    number["Bool"= true;
 
    Computer["Computer"]["Number"= number;
 
    StreamWriterBuilder builder;
    builder["commentStyle"= "None";
    builder["indentation"= "    ";  // Tab
    unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
 
    // 알파벳 순으로 write 된다.
    writer->write(Computer, &cout);
    writer->write(Computer, &json_file);
    cout << endl;  // add lf and flush
 
    json_file.close();
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.


같은 결과의 JSON_DATA.json 파일이 생성 된다.

읽기 예제

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ifstream json_dir("JSON_DATA.json");
    CharReaderBuilder builder;
    builder["collectComments"= false;
    Value value;
 
    JSONCPP_STRING errs;
    bool ok = parseFromStream(builder, json_dir, &value, &errs);
 
    if (ok == true)
    {
        cout << "CPU: " << value["CPU"<< endl;
        cout << "Program Python: " << value["Program"]["Python"<< endl;
        cout << "Computer Cable: " << value["Computer"]["Cable"<< endl;
        cout << "Computer Cable[0]: " << value["Computer"]["Cable"][0<< endl;
        cout << endl;
 
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"].get("Int"-1).asInt() << endl;
        // "Int" 값이 없으면 -1 반환.
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"]["Int"].asInt() << endl;
        // "Int" 값이 없으면 0 반환.
        cout << "Computer Number Double(as double): " << value["Computer"]["Number"].get("Double"-1).asDouble() << endl;
        // "Double" 값이 없으면 -1 반환.
        cout << "Computer Number Double(as string): " << value["Computer"]["Number"].get("Double""Empty").asString() << endl;
        // "Double" 값이 없으면 Empty 반환.
        cout << "Computer Number Bool(as bool): " << value["Computer"]["Number"].get("Bool"false).asBool() << endl;
        // "Bool" 값이 없으면 false 반환.
        cout << endl;
 
        cout << "Root size: " << value.size() << endl;
        cout << "Program size: " << value["Program"].size() << endl;
        cout << "Computer Cable size: " << value["Computer"]["Cable"].size() << endl;
        cout << endl;
 
        int size = value["Computer"]["Cable"].size();
        // size() 값을 for 문에서 그대로 비교하면 warning C4018가 발생 한다.
        for (int i = 0; i < size; i++)
            cout << "Computer Cable: " << value["Computer"]["Cable"][i] << endl;
        cout << endl;
 
        for (auto i : value["Computer"]["Cable"])
            cout << "Computer Cable: " << i << endl;
    }
    else
    {
        cout << "Parse failed." << endl;
    }
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.



반응형

'C, C++' 카테고리의 다른 글

Qt 스프라이트 애니매이션  (0) 2019.02.21
Qt 설치 및 간단한 사용 예  (4) 2019.01.16
Console 어플리케이션에 이미지 디스플레이 하기  (0) 2018.11.22
Python C API  (0) 2018.11.21
MySQL C API  (0) 2018.11.20
Posted by J-sean
: