[Lua, Json] lua에서 json 처리하기. json for lua

2016. 1. 15. 19:33프로그래밍/Script

728x90
728x90

여러 Json 모듈이 있다. 

http://lua-users.org/wiki/JsonModules


이 사람이 만든 게 encode_pretty가 맘에 들어서 한번 테스트 해봤다.

http://regex.info/blog/lua/json

예쁘게 출력이 없으면... 그 긴 json 파일이 일렬로 늘어서는 마법이..


대부분 file에서 읽어들여 처리하는 것이 없어 file 처리 스크립트를 만들었다.

딱히 뭐가 있는건 아니고 그냥 파일 열어서 디코딩하고 인코딩하고 쓰고..


코드 

https://github.com/ElementalKiss/Lua/tree/master/Json


jsonFileProcessor.lua

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
--[[
    Date : 2016.01.16 
    Creator : Elkiss
    Email : jominhyuk87@gmail.com
]]--
 
-- file read
function FileRead(filePath)
    local data = nil
    local handle = io.open(filePath, "r")
 
    if handle then
        data = json:decode(handle:read("*a"))
        io.close(handle)
    end
    
    return data
end
 
-- file write
function FileWrite(filePath, data, pretty)    
    local handle = io.open(filePath, "w+")
    
    if handle then
        if pretty then
            handle:write(json:encode_pretty(data))
        else
            handle:write(json:encode(data))
        end
        io.close(handle)
    end
end
cs


main.lua

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
-- import library
json = require('json')
require('jsonFileProcessor')
 
-- main function 
function main()
    local fileName = "test"
    local filePath = "../json/jsons/"..fileName..".json"
    local testJson = FileRead(filePath)
    
    -- for table print
    if testJson then
        for i = 1, #testJson, 1 do
            table.foreach(testJson[i], print)
        end
    end
    
    FileWrite(filePath, testJson)
    local filePath = "../json/jsons/"..fileName.."_pretty.json"
    FileWrite(filePath, testJson, true)
 
    return
end
 
-- call main
main()
cs


test_pretty.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
[ {
  "batters": {
    "batter": [ {
      "id": "1001",
      "type": "Regular"
    }, {
      "id": "1002",
      "type": "Chocolate"
    }, {
      "id": "1003",
      "type": "Blueberry"
    }, {
      "id": "1004",
      "type": "Devil's Food"
    } ]
  },
  "id": "0001",
  "name": "Cake",
  "ppu": 0.55,
  "topping": [ {
    "id": "5001",
    "type": "None"
  }, {
    "id": "5002",
    "type": "Glazed"
  }, {
    "id": "5005",
    "type": "Sugar"
  }, {
    "id": "5007",
    "type": "Powdered Sugar"
  }, {
    "id": "5006",
    "type": "Chocolate with Sprinkles"
  }, {
    "id": "5003",
    "type": "Chocolate"
  }, {
    "id": "5004",
    "type": "Maple"
  } ],
  "type": "donut"
},
    .................
} ]
cs


결과


728x90
반응형

'프로그래밍 > Script' 카테고리의 다른 글

[루아] Lua에서 .과 :의 차이(?) + OOP  (4) 2015.12.17
개론  (2) 2015.10.01
Lua와 C 바인딩  (0) 2015.09.20
Lua 메타테이블  (0) 2015.09.20
Lua 5.x와 4.0 호환성  (0) 2015.09.20
Lua 조건문, 반복문  (0) 2015.09.19
Lua 연산자  (0) 2015.09.19