main.lua 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "jsondemo"
  3. VERSION = "1.0.0"
  4. -- 引入必要的库文件(lua编写), 内部库不需要require
  5. sys = require("sys")
  6. log.info("main", PROJECT, VERSION)
  7. -- json库支持将 table 转为 字符串, 或者反过来, 字符串 转 table
  8. -- 若转换失败, 会返回nil值, 强烈建议在使用时添加额外的判断
  9. sys.taskInit(function()
  10. while 1 do
  11. sys.wait(1000)
  12. -- table 转为 字符串
  13. local t = {abc=123, def="123", ttt=true}
  14. local jdata = json.encode(t)
  15. log.info("json", jdata) --日志输出:{"ttt":true,"def":"123","abc":123}
  16. -- 字符串转table
  17. local str = "{\"abc\":1234545}" -- 字符串可以来源于任何地方,网络,文本,用户输入,都可以
  18. local t = json.decode(str)
  19. if t then
  20. -- 若解码成功,t不为nil
  21. log.info("json", "decode", t.abc) --日志输出:decode 1234545
  22. else
  23. -- 若解码失败,t为nil
  24. log.info("json", "decode failed")
  25. end
  26. -- lua中的table是 数组和hashmap的混合体
  27. -- 这对json来说会有一些困扰, 尤其是空的table
  28. local t = {abc={}}
  29. -- 假设从业务上需要输出 {"abc":[]}
  30. -- 实际会输出 {"abc": {}} , 空table是优先输出 hashmap (即字典模式)形式, 而非数组形式,Lua语言中数组优先级低于hashmap优先级
  31. log.info("json", "encode", json.encode(t)) --日志输出:encode {"abc":{}}
  32. -- 混合场景, json场景应避免使用
  33. t.abc.def = "123"
  34. t.abc[1] = 345
  35. -- 输出的内容是 {"abc":{"1":345,"def":"123"}}
  36. log.info("json", "encode2", json.encode(t)) --日志输出:encode2 {"abc":{"1":345,"def":"123"}}
  37. -- 浮点数演示
  38. log.info("json", json.encode({abc=1234.300})) --日志输出:{"abc":1234.300}
  39. -- 限制小数点到1位
  40. log.info("json", json.encode({abc=1234.300}, "1f")) --日志输出:{"abc":1234.3}
  41. local tmp = "ABC\r\nDEF\r\n"
  42. local tmp2 = json.encode({str=tmp}) --在JSON中,\r\n 被保留为字符串的一部分
  43. log.info("json", tmp2) --日志输出:{"str":"ABC\r\nDEF\r\n"}
  44. local tmp3 = json.decode(tmp2)
  45. log.info("json", "tmp3", tmp3.str, tmp3.str == tmp) --日志输出:tmp3 ABC
  46. --DEF
  47. -- true 注:true前存在一个TAB长度(这个TAB原因未知,但不影响使用)
  48. -- break
  49. log.info("json.null", json.encode({name=json.null})) --日志输出:{} 为空对象
  50. log.info("json.null", json.decode("{\"abc\":null}").abc == json.null) --日志输出:false 在 Lua 中,nil 是一种特殊类型,用于表示“无值”或“未定义”。它与任何其他值(包括自定义的 json.null)都不相等
  51. log.info("json.null", json.decode("{\"abc\":null}").abc == nil) --日志输出:false
  52. end
  53. end)
  54. -- 这里演示4G模块上网后,会自动点亮网络灯,方便用户判断模块是否正常开机
  55. sys.taskInit(function()
  56. while true do
  57. sys.wait(6000)
  58. if mobile.status() == 1 then
  59. gpio.set(27, 1)
  60. else
  61. gpio.set(27, 0)
  62. mobile.reset()
  63. end
  64. end
  65. end)
  66. -- 用户代码已结束---------------------------------------------
  67. -- 结尾总是这一句
  68. sys.run()
  69. -- sys.run()之后后面不要加任何语句!!!!!