From 53e9971edd9449024c2f8056db80313bd688affd Mon Sep 17 00:00:00 2001 From: Don Rouse Date: Thu, 25 Aug 2016 03:46:47 -0700 Subject: [PATCH] Add JSON pointer support to $data reference. --- lib/compile/util.js | 33 +++++++++++++++++++++++---------- lib/refs/json-schema-v5.json | 5 ++++- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/lib/compile/util.js b/lib/compile/util.js index f79a906..124be27 100644 --- a/lib/compile/util.js +++ b/lib/compile/util.js @@ -214,20 +214,33 @@ function getPath(currentPath, prop, jsonPointers) { } +var JSON_POINTER = /^#|\/(?:[^~]|~0|~1)*?$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, lvl, paths) { - var matches = $data.match(RELATIVE_JSON_POINTER); - if (!matches) throw new Error('Invalid relative JSON-pointer: ' + $data); - var up = +matches[1]; - var jsonPointer = matches[2]; - if (jsonPointer == '#') { - if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); - return paths[lvl - up]; + var up; + var jsonPointer; + var data; + var matches; + if ($data.charAt(0) == '/') { + matches = $data.match(JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = matches[0]; + data = 'data'; } + else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } - if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); - var data = 'data' + ((lvl - up) || ''); - if (!jsonPointer) return data; + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } var expr = data; var segments = jsonPointer.split('/'); diff --git a/lib/refs/json-schema-v5.json b/lib/refs/json-schema-v5.json index 8905d77..5964042 100644 --- a/lib/refs/json-schema-v5.json +++ b/lib/refs/json-schema-v5.json @@ -30,7 +30,10 @@ "properties": { "$data": { "type": "string", - "format": "relative-json-pointer" + "anyOf": [ + { "format": "relative-json-pointer" }, + { "format": "json-pointer" } + ] } }, "additionalProperties": false