1 --一个使用示例
2 package.cpath = "cjson/?.so;" .. package.cpath
3 local cjson = require("cjson")
4
5 local function is_json(str)
6 local success, result = pcall(cjson.decode, str)
7 return success
8 end
9
10 local test_str1 = '{"name": "John", "age": 30}'
11 local test_str2 = 'This is not a valid JSON string'
12
13 local if_str1_json = is_json(test_str1)
14 local if_str2_json = is_json(test_str2)
15
16 print(if_str1_json)
17 print(if_str2_json)
18
19 if if_str1_json then
20 print("test_str1 is a valid JSON")
21 else
22 print("test_str1 is not a valid JSON")
23 end
24
25 if if_str2_json then
26 print("test_str2 is a valid JSON")
27 else
28 print("test_str2 is not a valid JSON")
29 end