lua解析json

转载注明出处:点击打开链接

需要修改的json数据gui-config.json

[plain] view plain copy
  1. {  
  2.     "configs": [{  
  3.         "server": "JP3.ISS.TF",  
  4.         "server_port": 443,  
  5.         "password": "58603228",  
  6.         "method": "aes-256-cfb",  
  7.         "remarks": ""  
  8.     },  
  9.     {  
  10.         "server": "US1.ISS.TF",  
  11.         "server_port": 443,  
  12.         "password": "37382928",  
  13.         "method": "aes-256-cfb",  
  14.         "remarks": ""  
  15.     },  
  16.     {  
  17.         "server": "HK2.ISS.TF",  
  18.         "server_port": 8989,  
  19.         "password": "59434206",  
  20.         "method": "aes-256-cfb",  
  21.         "remarks": ""  
  22.     }],  
  23.     "strategy": null,  
  24.     "index": 0,  
  25.     "global": false,  
  26.     "enabled": true,  
  27.     "shareOverLan": false,  
  28.     "isDefault": false,  
  29.     "localPort": 1080,  
  30.     "pacUrl": null,  
  31.     "useOnlinePac": false,  
  32.     "availabilityStatistics": false  
  33. }  


LUA解析代码:

[plain] view plain copy
  1. function FileRead()  
  2.     local file = io.open("gui-config.json", "r");  
  3.     local json = file:read("*a");  
  4.     file:close();  
  5.     return json;  
  6. end  
  7.   
  8. function FileWrite()  
  9.     local file = io.open("gui-config.json", "w");  
  10.     file:close();  
  11. end  
  12.   
  13. local cjson = require("cjson");  
  14. local file = FileRead();  
  15. local json = cjson.decode(file);  
  16. for i, w in ipairs(json.configs) do  
  17.     print("server: " .. w.password)  
  18.     print("server_port: " .. w.server_port)  
  19.     print("password: " .. w.password)  
  20.     print("method: " .. w.method .. '\n')  
  21. end  

输出:

lua解析json