1.lua 5.3的安装
直接去官网下载
http://www.lua.org/ftp/lua-5.3.3.tar.gz
make macosx sudo make install
2.CSJON
编译lua-cjson库,用的是云风fork后修改的支持lua53 integer64的库,传送门:lua-cjson库
https://github.com/cloudwu/lua-cjson
版本:Lua CJSON 2.1
Makefile的改动:
LUA_VERSION = 5.3 #注意你的lua版本,可以用lua -v看 取小数点后一位 我的版本是
Lua 5.3.1 Copyright (C) 1994-2013 Lua.org, PUC-Rio
PREFIX = /usr/local 前缀路径,安装lua的时候用 make install 安装;可以cd /usr/local到该路径查看是否存在lua的相关库
原:CJSON_LDFLAGS = -shared
改:CJSON_LDFLAGS = -bundle -undefined dynamic_lookup
这里就是OSX和Unix的区别,bundle是Mac使用的文件格式,如果不使用这些选项,可能引起“multiple lua vms detected”错误
添加:
CJSON_CFLAGS += -DUSE_INTERNAL_FPCONV
CJSON_CFLAGS += -DIEEE_BIG_ENDIAN
CJSON_CFLAGS += -pthread -DMULTIPLE_THREADS
示例代码
解析JSON
local cjson = require "cjson" local sampleJson = [[{"age":"23","testArray":{"array":[8,9,11,14,25]},"Himi":"himigame.com"}]]; --解析json字符串 local data = cjson.decode(sampleJson); --打印json字符串中的age字段 print(data["age"]); --打印数组中的第一个值(lua默认是从0开始计数) print(data["testArray"]["array"][1]);
编码JSON
local cjson = require "cjson" local retTable = {}; --最终产生json的表 --顺序数值 local intDatas = {}; intDatas[1] = 100; intDatas[2] = "100"; --数组 local aryDatas = {}; aryDatas[1] = {}; aryDatas[1]["键11"] = "值11"; aryDatas[1]["键12"] = "值12"; aryDatas[2] = {}; aryDatas[2]["键21"] = "值21"; aryDatas[2]["键22"] = "值22"; --对Table赋值 retTable["键1"] = "值1"; retTable[2] = 123; retTable["int_datas"] = intDatas; retTable["aryDatas"] = aryDatas; --将表数据编码成json字符串 local jsonStr = cjson.encode(retTable); print(jsonStr); --结果是:{"int_datas":[100,"100"],"2":123,"键1":"值1","aryDatas":[{"键12":"值12","键11":"值11"},{"键21":"值21","键22":"值22"}]}