diff options
Diffstat (limited to 'tests/sort_json.lua')
-rw-r--r-- | tests/sort_json.lua | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/tests/sort_json.lua b/tests/sort_json.lua new file mode 100644 index 0000000..c95ab3c --- /dev/null +++ b/tests/sort_json.lua | |||
@@ -0,0 +1,61 @@ | |||
1 | -- NOTE: This will only work for simple tests. It doesn't parse strings so if | ||
2 | -- you put any symbols like {?[], inside of a string literal then it will break | ||
3 | -- The point of this function is to test basic structures, and not test JSON | ||
4 | -- strings | ||
5 | |||
6 | local function sort_callback(str) | ||
7 | local inside = str:sub(2, -2) | ||
8 | |||
9 | local parts = {} | ||
10 | local buffer = "" | ||
11 | local pos = 1 | ||
12 | |||
13 | while true do | ||
14 | if pos > #inside then | ||
15 | break | ||
16 | end | ||
17 | |||
18 | local append | ||
19 | |||
20 | local parens = inside:match("^%b{}", pos) | ||
21 | if parens then | ||
22 | pos = pos + #parens | ||
23 | append = sort_callback(parens) | ||
24 | else | ||
25 | local array = inside:match("^%b[]", pos) | ||
26 | if array then | ||
27 | pos = pos + #array | ||
28 | append = array | ||
29 | else | ||
30 | local front = inside:sub(pos, pos) | ||
31 | pos = pos + 1 | ||
32 | |||
33 | if front == "," then | ||
34 | table.insert(parts, buffer) | ||
35 | buffer = "" | ||
36 | else | ||
37 | append = front | ||
38 | end | ||
39 | end | ||
40 | end | ||
41 | |||
42 | if append then | ||
43 | buffer = buffer .. append | ||
44 | end | ||
45 | end | ||
46 | |||
47 | if buffer ~= "" then | ||
48 | table.insert(parts, buffer) | ||
49 | end | ||
50 | |||
51 | table.sort(parts) | ||
52 | |||
53 | return "{" .. table.concat(parts, ",") .. "}" | ||
54 | end | ||
55 | |||
56 | local function sort_json(str) | ||
57 | return (str:gsub("%b{}", sort_callback)) | ||
58 | end | ||
59 | |||
60 | |||
61 | return sort_json | ||