Comparison

util/jsonpointer.lua @ 12131:b4c0efff8dd3

util.jsonpointer: Resolve JSON Pointers per RFC 6901
author Kim Alvefur <zash@zash.se>
date Wed, 29 Dec 2021 16:52:09 +0100
child 12496:87c3d45208ef
comparison
equal deleted inserted replaced
12130:c4ca226ff386 12131:b4c0efff8dd3
1 local function unescape_token(escaped_token)
2 local unescaped = escaped_token:gsub("~1", "/"):gsub("~0", "~")
3 return unescaped
4 end
5
6 local function resolve_json_pointer(ref, path)
7 local ptr_len = #path + 1
8 for part, pos in path:gmatch("/([^/]*)()") do
9 local token = unescape_token(part)
10 if not (type(ref) == "table") then
11 return nil
12 end
13 local idx = next(ref)
14 local new_ref
15
16 if type(idx) == "string" then
17 new_ref = ref[token]
18 elseif math.type(idx) == "integer" then
19 local i = tonumber(token)
20 if token == "-" then
21 i = #ref + 1
22 end
23 new_ref = ref[i]
24 else
25 return nil, "invalid-table"
26 end
27
28 if pos == ptr_len then
29 return new_ref
30 elseif type(new_ref) == "table" then
31 ref = new_ref
32 elseif not (type(ref) == "table") then
33 return nil, "invalid-path"
34 end
35
36 end
37 return ref
38 end
39
40 return { resolve = resolve_json_pointer }