Lua-cjson库的官方网站

https://www.kyne.com.au/~mark/software/lua-cjson.php

可以用luarocks安装cjson库

  1. luarocks install lua-cjson

例子1 decode—将json字符串解析成lua-table类型

  1. json_text = '[true, {"foo":"bar"}]'
  2. json_value = cjson.decode(json_text)
  3. -- Returns: '[true,{"foo":"bar"}]'
  4. for key, value in pairs(json_value) do
  5. if key == 1 then
  6. print(key, value)
  7. elseif key == 2 then
  8. for k, v in pairs(value) do
  9. print(k, v)
  10. end
  11. end
  12. end

结果如下:

  1. 1 true
  2. foo bar
  1. local cjson = require "cjson"
  2. local sampleJson = [[{"age":"23","testArray":{"array":[8,9,11,14,25]},"Himi":"himigame.com"}]];
  3. --解析json字符串
  4. local data = cjson.decode(sampleJson);
  5. --打印json字符串中的age字段
  6. print(data["age"]);
  7. --打印数组中的第一个值(lua默认是从0开始计数)
  8. print(data["testArray"]["array"][1]);

例子2 encode—将lua-table类型装换成json字符串

  1. local cjson = require "cjson"
  2. list = {foo = "bar"}
  3. json_str = cjson.encode(list)
  4. print(json_str)

结果如下:

  1. {"foo":"bar"}
  1. local cjson = require "cjson"
  2. local retTable = {}; --最终产生json的表
  3. --顺序数值
  4. local intDatas = {};
  5. intDatas[1] = 100;
  6. intDatas[2] = "100";
  7. --数组
  8. local aryDatas = {};
  9. aryDatas[1] = {};
  10. aryDatas[1]["键11"] = "值11";
  11. aryDatas[1]["键12"] = "值12";
  12. aryDatas[2] = {};
  13. aryDatas[2]["键21"] = "值21";
  14. aryDatas[2]["键22"] = "值22";
  15. --对Table赋值
  16. retTable["键1"] = "值1";
  17. retTable[2] = 123;
  18. retTable["int_datas"] = intDatas;
  19. retTable["aryDatas"] = aryDatas;
  20. --将表数据编码成json字符串
  21. local jsonStr = cjson.encode(retTable);
  22. print(jsonStr);
  23. --结果是:{"int_datas":[100,"100"],"2":123,"键1":"值1","aryDatas":[{"键12":"值12","键11":"值11"},{"键21":"值21","键22":"值22"}]}