lua 的 cjson 安裝,使用

1. 背景:php

  虛擬機安裝的luajit  沒有 cjson 庫,就不能對 table 進行 編碼操做,手動安裝一個。git

2. 安裝:json

  cjson下載地址:http://www.kyne.com.au/~mark/software/lua-cjson.php數組

  下載文件 lua-cjson-2.1.0.tar.gzui

  放到虛擬機一個目錄,解壓,先 make 一下編碼

cc -c -O3 -Wall -pedantic -DNDEBUG  -I/usr/local/include -fpic -o lua_cjson.o lua_cjson.c lua_cjson.c:43:17: error: lua.h: No such file or directory lua_cjson.c:44:21: error: lauxlib.h: No such file or directory lua_cjson.c:192: error: expected ‘)’ before ‘*’ token lua_cjson.c:206: error: expected ‘)’ before ‘*’ token lua_cjson.c:218: error: expected ‘)’ before ‘*’ token lua_cjson.c:237: error: expected ‘)’ before ‘*’ token lua_cjson.c:266: error: expected ‘)’ before ‘*’ token lua_cjson.c:279: error: expected ‘)’ before ‘*’ token

  這個報錯是沒有找到 lua 源碼,find 一下lua.h這個文件,發現位於好幾個路徑下。由於歷史緣由,均可以使用,選擇一個。lua

/usr/local/src/LuaJIT-2.1.0-beta2/src/lua.h /usr/local/luajit/include/luajit-2.1/lua.h /usr/local/include/luajit-2.0/lua.h

  修改Makefile文件,修改default配置爲spa

LUA_VERSION =       5.1 TARGET = cjson.so PREFIX =            /usr/local #CFLAGS =            -g -Wall -pedantic -fno-inline CFLAGS =            -O3 -Wall -pedantic -DNDEBUG CJSON_CFLAGS =      -fpic CJSON_LDFLAGS =     -shared LUA_INCLUDE_DIR =   /usr/local/src/LuaJIT-2.1.0-beta2/src/ LUA_CMODULE_DIR =   $(PREFIX)/lib/lua/$(LUA_VERSION) LUA_MODULE_DIR =    $(PREFIX)/share/lua/$(LUA_VERSION) LUA_BIN_DIR =       $(PREFIX)/bin

  主要是修改了LUA_INCLUDE_DIR用於安裝cjson;修改了PREFIX變量用來改變編譯結果文件輸出的路徑。3d

  保存,執行命令code

make && make install cc -c -O3 -Wall -pedantic -DNDEBUG  -I/usr/local/src/LuaJIT-2.1.0-beta2/src/ -fpic -o lua_cjson.o lua_cjson.c cc -c -O3 -Wall -pedantic -DNDEBUG  -I/usr/local/src/LuaJIT-2.1.0-beta2/src/ -fpic -o strbuf.o strbuf.c cc -c -O3 -Wall -pedantic -DNDEBUG  -I/usr/local/src/LuaJIT-2.1.0-beta2/src/ -fpic -o fpconv.o fpconv.c cc -shared -o cjson.so lua_cjson.o strbuf.o fpconv.o cp cjson.so /usr/local/lib/lua/5.1/ chmod 755 /usr/local/lib/lua/5.1/cjson.so

 

3. 使用:

 

  編碼:

local cjson2 = require "cjson"
-- 布爾類型 local lua_bool = true print(cjson2.encode(lua_bool)) -- 數組類型 local lua_array = {1, 2, 3, 4, 5, 6} print(cjson2.encode(lua_array)) -- 數值類型 local lua_number = 6.66 print(cjson2.encode(lua_number)) -- 字符串類型 local lua_string = "I am test1280" print(cjson2.encode(lua_string)) -- 對象類型 local lua_object = { ["name"] = "Jiang", ["age"] = 24, ["addr"] = "BeiJing", ["email"] = "1569989xxxx@126.com", ["tel"] = {f='123',d='456'} } print(cjson2.encode(lua_object))

===================================

 true
 [1,2,3,4,5,6]
 6.66
 "I am test1280"
 {"addr":"BeiJing","tel":{"d":"456","f":"123"},"age":24,"name":"Jiang","email":"1569989xxxx@126.com"}

  解碼:

json = require "cjson" a= '{"deviceid": "dev","taskid": "","tasktype": "3101","configlist":{"sd_new_old_cp_switch":{"vod":"gitvlive"}}}' atb=json.decode(a) print(atb.deviceid) print(atb.configlist) print(atb.configlist.sd_new_old_cp_switch.vod)

  通常 用的比較多的就是 把 json 字符串 decode 成 lua 的 table 數據類型。

相關文章
相關標籤/搜索