util/jsonpointer.lua
author Kim Alvefur <zash@zash.se>
Mon, 07 Mar 2022 00:35:29 +0100
changeset 12392 50fcd3879482
parent 12135 b4c0efff8dd3
child 12500 87c3d45208ef
permissions -rw-r--r--
spelling: non-existing mistakes (thanks timeless)

local function unescape_token(escaped_token)
	local unescaped = escaped_token:gsub("~1", "/"):gsub("~0", "~")
	return unescaped
end

local function resolve_json_pointer(ref, path)
	local ptr_len = #path + 1
	for part, pos in path:gmatch("/([^/]*)()") do
		local token = unescape_token(part)
		if not (type(ref) == "table") then
			return nil
		end
		local idx = next(ref)
		local new_ref

		if type(idx) == "string" then
			new_ref = ref[token]
		elseif math.type(idx) == "integer" then
			local i = tonumber(token)
			if token == "-" then
				i = #ref + 1
			end
			new_ref = ref[i]
		else
			return nil, "invalid-table"
		end

		if pos == ptr_len then
			return new_ref
		elseif type(new_ref) == "table" then
			ref = new_ref
		elseif not (type(ref) == "table") then
			return nil, "invalid-path"
		end

	end
	return ref
end

return { resolve = resolve_json_pointer }