Skip to content
Myr

feat(validator): add support for JSON array path validation (#563)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* refactor(JSONPath): improve typing of JSONPath * chore(vscode-settings): add deno.enable=false * fix(validator): add null to type Type def * feat(JSON-Path): add support for array JSONPath-Plus syntax * fix(validator): update isRequired to pass valid bool types * test: update tests for isRequired validator * feat(validator): add support for JSON array path validation * chore(deno): denoify array support changes * fix(validator): type check all vals in array * chore(deno): denoify changes * test(validator): add tests for array type checking * fix(validator): change JSONPrimative to JSONPrimitive * refactor(json): More compatible with https://jsonpath.com/. * implementation of `asArray` * fix(validator): update JSONPath implementation and add isArray check in validation * fix(validator): fix typing errors on SchemaToProp * Revert "fix(validator): fix typing errors on SchemaToProp" This reverts commit b8ddef85d0759325d9cb2d8b227dddf6c0cac362. * fix(validator): fix SchemaToProp error for VTypeArrays * chore(deno): denoify

authored by Derrick Farris · committed by GitHub · parent 13ce2ee · Browse files · 10 files+626 added−87 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Taku Amano <taku@taaas.jp>
  • Co-authored-by: Yusuke Wada <yusuke@kamawada.com>

Diff stats

10 files+626 added−87 removed

  • tests:+321 added−4 removed
  • other:+305 added−83 removed

10 files+626 added−87 removed

modified:.vscode/settings.json+3 added-7 removed
modified:deno_dist/middleware/validator/middleware.ts+26 added-3 removed
modified:deno_dist/middleware/validator/validator.ts+95 added-23 removed
1import { JSONPath } from '../../utils/json.ts'2import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json.ts'3import { rule } from './rule.ts'4import { sanitizer } from './sanitizer.ts'56type Target = 'query' | 'header' | 'body' | 'json'6type Type = string | number | boolean | object | undefined7type Type = JSONPrimitive | JSONObject | JSONArray | File8type Rule = (value: Type) => boolean9type Sanitizer = (value: Type) => Type1011export class Validator {
14 unmodified lines
26type VOptions = {27 target: Target28 key: string29 type?: 'string' | 'number' | 'boolean' | 'object'30 isArray?: boolean31}3233export abstract class VBase {34 type: 'string' | 'number' | 'boolean' | 'object'35 target: Target36 key: string37 rules: Rule[]38 sanitizers: Sanitizer[]39 isArray: boolean40 private _message: string | undefined41 private _optional: boolean3942 constructor(options: VOptions) {43 this.target = options.target44 this.key = options.key45 this.type = options.type || 'string'46 this.rules = []47 this.sanitizers = []48 this.isArray = options.isArray || false49 this._optional = false50 }5152 addRule = (rule: Rule) => {
7 unmodified lines
60 }6162 isRequired = () => {63 return this.addRule((value: unknown) => {61 if (value) return true64 if (value !== undefined && value !== null && value !== '') return true65 return false66 })67 }68
48 unmodified lines
117 const body = await req.parseBody()118 value = body[this.key]119 }120 if (this.target === 'json') {118 const obj = await req.json()121 const obj = (await req.json()) as JSONObject122 value = JSONPath(obj, this.key)123 }124125 result.value = value126 result.isValid = this.validateValue(value)127125 if (result.isValid == false) {128 if (result.isValid === false) {129 if (this._message) {130 result.message = this._message131 } else {132 const valToStr = Array.isArray(value)133 ? `[${value134 .map((val) =>135 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val136 )137 .join(', ')}]`138 : value139 switch (this.target) {140 case 'query':131 result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${value}`141 result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${valToStr}`142 break143 case 'header':134 result.message = `Invalid Value: the request header "${this.key}" is invalid - ${value}`144 result.message = `Invalid Value: the request header "${this.key}" is invalid - ${valToStr}`145 break146 case 'body':137 result.message = `Invalid Value: the request body "${this.key}" is invalid - ${value}`147 result.message = `Invalid Value: the request body "${this.key}" is invalid - ${valToStr}`148 break149 case 'json':140 result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${value}`150 result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${valToStr}`151 break152 }153 }154 }
1 unmodified line
156 }157158 private validateValue = (value: Type): boolean => {159 // Check type150 if (typeof value !== this.type) {151 if (this._optional && typeof value === 'undefined') {152 // Do nothing.153 // The value is allowed to be `undefined` if it is `optional`154 } else {160 if (this.isArray) {161 if (!Array.isArray(value)) {162 return false163 }157 }164159 // Sanitize160 for (const sanitizer of this.sanitizers) {161 value = sanitizer(value)162 }165 for (const val of value) {166 if (typeof val !== this.type) {167 // Value is of wrong type here168 // If not optional, or optional and not undefined, return false169 if (!this._optional || typeof val !== 'undefined') return false170 }171 }172164 for (const rule of this.rules) {165 if (!rule(value)) {166 return false173 // Sanitize174 for (const sanitizer of this.sanitizers) {175 value = value.map((innerVal) => sanitizer(innerVal)) as JSONArray176 }177178 for (const rule of this.rules) {179 for (const val of value) {180 if (!rule(val)) {181 return false182 }183 }184 }185 return true186 } else {187 if (typeof value !== this.type) {188 if (this._optional && typeof value === 'undefined') {189 // Do nothing.190 // The value is allowed to be `undefined` if it is `optional`191 } else {192 return false193 }194 }195196 // Sanitize197 for (const sanitizer of this.sanitizers) {198 value = sanitizer(value)199 }200201 for (const rule of this.rules) {202 if (!rule(value)) {203 return false204 }205 }206 return true207 }169 return true208 }209}210211export class VString extends VBase {
1 unmodified line
213 super(options)214 this.type = 'string'215 }216217 asArray = () => {218 return new VStringArray(this)219 }220221 isEmpty = (222 options: {223 ignore_whitespace: boolean224 } = { ignore_whitespace: false }
41 unmodified lines
266 super(options)267 this.type = 'number'268 }269270 asArray = () => {271 return new VNumberArray(this)272 }273274 isGte = (min: number) => {275 return this.addRule((value) => rule.isGte(value as number, min))276 }277
7 unmodified lines
285 super(options)286 this.type = 'boolean'287 }288289 asArray = () => {290 return new VBooleanArray(this)291 }292293 isTrue = () => {294 return this.addRule((value) => rule.isTrue(value as boolean))295 }296
7 unmodified lines
304 super(options)305 this.type = 'object'306 }307}308309export class VNumberArray extends VNumber {310 isArray: true311 constructor(options: VOptions) {312 super(options)313 this.isArray = true314 }315}316export class VStringArray extends VString {317 isArray: true318 constructor(options: VOptions) {319 super(options)320 this.isArray = true321 }322}323export class VBooleanArray extends VBoolean {324 isArray: true325 constructor(options: VOptions) {326 super(options)327 this.isArray = true328 }329}
modified:deno_dist/utils/json.ts+30 added-12 removed
modified:src/middleware/validator/middleware.test.ts+38 added-3 removed
385 unmodified lines
386 },387 post: {388 title: v.json('post.title').isAlpha(),389 content: v.json('post.content'),390 }390 },391 })),392 (c) => {393 const header = c.req.valid().header394 const post = c.req.valid().post395 return c.json({header, post})395 return c.json({ header, post })396 }397 )398399 it('Should return 200 response', async () => {
12 unmodified lines
412 body: JSON.stringify(json),413 })414 const res = await app.request(req)415 expect(res.status).toBe(200)416 expect(await res.json()).toEqual({header: headers, post: json.post})416 expect(await res.json()).toEqual({ header: headers, post: json.post })417 })418419 it('Should return 400 response - missing a required header', async () => {420 const json = {
9 unmodified lines
430 const res = await app.request(req)431 expect(res.status).toBe(400)432 })433})434435describe('Array values', () => {436 const app = new Hono()437 app.post(438 '/post',439 validator((v) => ({440 post: {441 title: v.json('post.title').isAlpha(),442 tags: v.json('post.tags').asArray().isRequired(),443 ids: v.json('post.ids').asNumber().asArray(),444 },445 })),446 (c) => {447 const res = c.req.valid()448 return c.json({ tag1: res.post.tags[0] })449 }450 )451452 it('Should return 200 response', async () => {453 const json = {454 post: {455 title: 'foo',456 tags: ['Workers', 'Deno', 'Bun'],457 ids: [1, 3, 5],458 },459 }460 const req = new Request('http://localhost/post', {461 method: 'POST',462 body: JSON.stringify(json),463 })464 const res = await app.request(req)465 expect(res.status).toBe(200)466 expect(await res.json()).toEqual({ tag1: 'Workers' })467 })468})
modified:src/middleware/validator/middleware.ts+26 added-3 removed
1import type { Context } from '../../context'2import type { Environment, Next, ValidatedData } from '../../hono'3import { VBase, Validator } from './validator'4import type { VString, VNumber, VBoolean, VObject, ValidateResult } from './validator'4import type {5 VString,6 VNumber,7 VBoolean,8 VObject,9 VNumberArray,10 VStringArray,11 VBooleanArray,12 ValidateResult,13} from './validator'1415type Schema = {7 [key: string]: VString | VNumber | VBoolean | VObject | Schema16 [key: string]:17 | VString18 | VNumber19 | VBoolean20 | VObject21 | VStringArray22 | VNumberArray23 | VBooleanArray24 | Schema25}2627type SchemaToProp<T> = {11 [K in keyof T]: T[K] extends VNumber28 [K in keyof T]: T[K] extends VNumberArray29 ? number[]30 : T[K] extends VBooleanArray31 ? boolean[]32 : T[K] extends VStringArray33 ? string[]34 : T[K] extends VNumber35 ? number36 : T[K] extends VBoolean37 ? boolean38 : T[K] extends VString
86 unmodified lines
modified:src/middleware/validator/validator.test.ts+194 added
125 unmodified lines
126 expect(res.message).toBe(messages.join('\n'))127 })128})129130describe('Handle required values', () => {131 const v = new Validator()132133 const req = new Request('http://localhost/', {134 method: 'POST',135 body: JSON.stringify({ comment: null, name: 'John', admin: false }),136 })137138 it('Should be valid - `name` is required', async () => {139 const validator = v.json('name').isRequired()140 const res = await validator.validate(req)141 expect(res.isValid).toBe(true)142 })143144 it('Should be invalid - `comment` is required but missing', async () => {145 const validator = v.json('comment').isRequired()146 const res = await validator.validate(req)147 expect(res.isValid).toBe(false)148 })149150 it('Should be valid - `admin` is required and present, although falsey', async () => {151 const validator = v.json('admin').asBoolean().isRequired()152 const res = await validator.validate(req)153 expect(res.isValid).toBe(true)154 expect(res.value).toBe(false)155 })156})157158describe('Handle optional values', () => {159 const v = new Validator()160161 const req = new Request('http://localhost/', {
36 unmodified lines
198 const messages = ['Invalid Value: the JSON body "published" is invalid - true']199 expect(res.message).toBe(messages.join('\n'))200 })201})202203describe('Handle array paths', () => {204 const v = new Validator()205206 const body = {207 posts: [208 {209 id: 12411,210 title: 'This is title #1',211 published: true,212 rating: [true, 'cool'],213 awesome: true,214 testing: false,215 },216 {217 id: 12412,218 title: 'This is title #2',219 published: true,220 rating: [false],221 awesome: 'true',222 testing: true,223 },224 {225 id: 12413,226 title: 'This is title #3',227 published: false,228 rating: [true, 'lame'],229 awesome: false,230 },231 ],232 }233234 const req = new Request('http://localhost/', {235 method: 'POST',236 body: JSON.stringify(body),237 })238239 it('Should validate targeted path in array', async () => {240 const validator = v.json('posts[*].published').asArray().asBoolean().isRequired()241 const res = await validator.validate(req)242 expect(res.isValid).toBe(true)243 expect(res.message).toBeUndefined()244 expect(res.value).toEqual([true, true, false])245 })246247 it('Should allow nested array paths', async () => {248 const validator = v.json('posts[*].rating[0]').asArray().asBoolean().isRequired()249 const res = await validator.validate(req)250 expect(res.isValid).toBe(true)251 expect(res.message).toBeUndefined()252 expect(res.value).toEqual([true, false, true])253 })254255 it('Should allow optional array paths', async () => {256 const validator = v.json('posts[*].rating[1]').asArray().isOptional()257 const res = await validator.validate(req)258 expect(res.isValid).toBe(true)259 expect(res.message).toBeUndefined()260 expect(res.value).toEqual(['cool', undefined, 'lame'])261 })262263 it('Should provide error with invalid array paths', async () => {264 const validator = v.json('posts[*].rating[3]').asArray()265 const res = await validator.validate(req)266 expect(res.isValid).toBe(false)267 const messages = [268 'Invalid Value: the JSON body "posts[*].rating[3]" is invalid - [undefined, undefined, undefined]',269 ]270 expect(res.message).toBe(messages.join('\n'))271 expect(res.value).toEqual([undefined, undefined, undefined])272 })273274 it('Should prevent invalid types within array', async () => {275 const validator = v.json('posts[*].awesome').asArray().asBoolean()276 const res = await validator.validate(req)277 expect(res.isValid).toBe(false)278 const messages = [279 'Invalid Value: the JSON body "posts[*].awesome" is invalid - [true, "true", false]',280 ]281 expect(res.message).toBe(messages.join('\n'))282 expect(res.value).toEqual([true, 'true', false])283 })284285 it('Should allow undefined values when optional', async () => {286 const validator = v.json('posts[*].testing').asArray().asBoolean().isOptional()287 const res = await validator.validate(req)288 expect(res.isValid).toBe(true)289 expect(res.value).toEqual([false, true, undefined])290 })291})292293describe('Validate with asArray', () => {294 const v = new Validator()295 const json = {296 post: {297 title: ['Hello'],298 flags: [true, false],299 published: [true],300 comments: [301 {302 title: 'abc',303 author: 'John',304 category: 'Heroes',305 flags: [true, false],306 },307 {308 title: 'def',309 author: 'Dave',310 flags: [false, true],311 },312 ],313 },314 }315316 const req = new Request('http://localhost/', {317 method: 'POST',318 body: JSON.stringify(json),319 })320321 it('Should validate array values', async () => {322 const validator = v.json('post.title').asArray().isAlpha()323 const res = await validator.validate(req)324 expect(res.isValid).toBe(true)325 })326327 it('Should validate array values - specify with `*`', async () => {328 const validator = v.json('post.comments[*].title').asArray().isAlpha()329 const res = await validator.validate(req)330 expect(res.isValid).toBe(true)331 })332333 it('Should return the same result for `.asArray().as{Type}()` and `.as{Type}().asArray()', async () => {334 const validator1 = v.json('post.flags').asArray().asBoolean().isRequired()335 const validator2 = v.json('post.flags').asBoolean().asArray().isRequired()336 const res1 = await validator1.validate(req)337 const res2 = await validator2.validate(req)338339 expect(res1.isValid).toBe(true)340 expect(res1.message).toBeUndefined()341 expect(res1.value).toEqual([true, false])342343 // Entire responses should be equal344 expect(res1).toEqual(res2)345 })346347 it('Should fail validation if value is array but `.asArray()` not called', async () => {348 const validator = v.json('post.flags').asBoolean().isRequired()349 const res = await validator.validate(req)350 expect(res.isValid).toBe(false)351 const messages = ['Invalid Value: the JSON body "post.flags" is invalid - [true, false]']352 expect(res.message).toBe(messages.join('\n'))353 expect(res.value).toEqual([true, false])354 })355356 it('Should pass validation if `isRequired` and path has no missing entries', async () => {357 const validator = v.json('post.comments[*].author').asArray().isRequired()358 const res = await validator.validate(req)359 expect(res.isValid).toBe(true)360 })361362 it('Should fail validation if `isRequired` and missing entry for path', async () => {363 const validator = v.json('post.comments[*].heroes').asArray().isRequired()364 const res = await validator.validate(req)365 expect(res.isValid).toBe(false)366 })367})
modified:src/middleware/validator/validator.ts+95 added-23 removed
1import { JSONPath } from '../../utils/json'2import type { JSONObject, JSONPrimitive, JSONArray } from '../../utils/json'3import { rule } from './rule'4import { sanitizer } from './sanitizer'56type Target = 'query' | 'header' | 'body' | 'json'6type Type = string | number | boolean | object | undefined7type Type = JSONPrimitive | JSONObject | JSONArray | File8type Rule = (value: Type) => boolean9type Sanitizer = (value: Type) => Type1011export class Validator {
14 unmodified lines
26type VOptions = {27 target: Target28 key: string29 type?: 'string' | 'number' | 'boolean' | 'object'30 isArray?: boolean31}3233export abstract class VBase {34 type: 'string' | 'number' | 'boolean' | 'object'35 target: Target36 key: string37 rules: Rule[]38 sanitizers: Sanitizer[]39 isArray: boolean40 private _message: string | undefined41 private _optional: boolean3942 constructor(options: VOptions) {43 this.target = options.target44 this.key = options.key45 this.type = options.type || 'string'46 this.rules = []47 this.sanitizers = []48 this.isArray = options.isArray || false49 this._optional = false50 }5152 addRule = (rule: Rule) => {
7 unmodified lines
60 }6162 isRequired = () => {63 return this.addRule((value: unknown) => {61 if (value) return true64 if (value !== undefined && value !== null && value !== '') return true65 return false66 })67 }68
48 unmodified lines
117 const body = await req.parseBody()118 value = body[this.key]119 }120 if (this.target === 'json') {118 const obj = await req.json()121 const obj = (await req.json()) as JSONObject122 value = JSONPath(obj, this.key)123 }124125 result.value = value126 result.isValid = this.validateValue(value)127125 if (result.isValid == false) {128 if (result.isValid === false) {129 if (this._message) {130 result.message = this._message131 } else {132 const valToStr = Array.isArray(value)133 ? `[${value134 .map((val) =>135 val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val136 )137 .join(', ')}]`138 : value139 switch (this.target) {140 case 'query':131 result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${value}`141 result.message = `Invalid Value: the query parameter "${this.key}" is invalid - ${valToStr}`142 break143 case 'header':134 result.message = `Invalid Value: the request header "${this.key}" is invalid - ${value}`144 result.message = `Invalid Value: the request header "${this.key}" is invalid - ${valToStr}`145 break146 case 'body':137 result.message = `Invalid Value: the request body "${this.key}" is invalid - ${value}`147 result.message = `Invalid Value: the request body "${this.key}" is invalid - ${valToStr}`148 break149 case 'json':140 result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${value}`150 result.message = `Invalid Value: the JSON body "${this.key}" is invalid - ${valToStr}`151 break152 }153 }154 }
1 unmodified line
156 }157158 private validateValue = (value: Type): boolean => {159 // Check type150 if (typeof value !== this.type) {151 if (this._optional && typeof value === 'undefined') {152 // Do nothing.153 // The value is allowed to be `undefined` if it is `optional`154 } else {160 if (this.isArray) {161 if (!Array.isArray(value)) {162 return false163 }157 }164159 // Sanitize160 for (const sanitizer of this.sanitizers) {161 value = sanitizer(value)162 }165 for (const val of value) {166 if (typeof val !== this.type) {167 // Value is of wrong type here168 // If not optional, or optional and not undefined, return false169 if (!this._optional || typeof val !== 'undefined') return false170 }171 }172164 for (const rule of this.rules) {165 if (!rule(value)) {166 return false173 // Sanitize174 for (const sanitizer of this.sanitizers) {175 value = value.map((innerVal) => sanitizer(innerVal)) as JSONArray176 }177178 for (const rule of this.rules) {179 for (const val of value) {180 if (!rule(val)) {181 return false182 }183 }184 }185 return true186 } else {187 if (typeof value !== this.type) {188 if (this._optional && typeof value === 'undefined') {189 // Do nothing.190 // The value is allowed to be `undefined` if it is `optional`191 } else {192 return false193 }194 }195196 // Sanitize197 for (const sanitizer of this.sanitizers) {198 value = sanitizer(value)199 }200201 for (const rule of this.rules) {202 if (!rule(value)) {203 return false204 }205 }206 return true207 }169 return true208 }209}210211export class VString extends VBase {
1 unmodified line
213 super(options)214 this.type = 'string'215 }216217 asArray = () => {218 return new VStringArray(this)219 }220221 isEmpty = (222 options: {223 ignore_whitespace: boolean224 } = { ignore_whitespace: false }
41 unmodified lines
266 super(options)267 this.type = 'number'268 }269270 asArray = () => {271 return new VNumberArray(this)272 }273274 isGte = (min: number) => {275 return this.addRule((value) => rule.isGte(value as number, min))276 }277
7 unmodified lines
285 super(options)286 this.type = 'boolean'287 }288289 asArray = () => {290 return new VBooleanArray(this)291 }292293 isTrue = () => {294 return this.addRule((value) => rule.isTrue(value as boolean))295 }296
7 unmodified lines
304 super(options)305 this.type = 'object'306 }307}308309export class VNumberArray extends VNumber {310 isArray: true311 constructor(options: VOptions) {312 super(options)313 this.isArray = true314 }315}316export class VStringArray extends VString {317 isArray: true318 constructor(options: VOptions) {319 super(options)320 this.isArray = true321 }322}323export class VBooleanArray extends VBoolean {324 isArray: true325 constructor(options: VOptions) {326 super(options)327 this.isArray = true328 }329}
modified:src/utils/json.test.ts+89 added-1 removed
1import type { JSONArray } from './json'2import { JSONPath } from './json'34describe('JSONPath', () => {5 const data = {
4 unmodified lines
10 age: 20,11 },12 tags: ['foo', 'bar', { framework: 'Hono' }],13 },14 relatedPosts: [15 {16 title: 'HelloWorld',17 author: {18 name: 'The Flash',19 age: 32,20 },21 tags: ['flash', 'marvel'],22 },23 {24 title: 'Hello World',25 author: {26 name: 'Spiderman',27 age: 26,28 },29 tags: ['spider', 'man'],30 },31 {32 title: 'World. Hello!',33 author: {34 name: 'Batman',35 age: 45,36 },37 tags: ['bat', 'man'],38 },39 ],40 releases: [41 {42 code: 'buster',43 amd64: true,44 },45 {46 code: 'stretch',47 amd64: true,48 },49 {50 code: 'potato',51 },52 ],53 nestedArray: [[[1]]],54 }5556 it('Should return the string or number pointed by JSON Path', () => {57 expect(JSONPath(data, 'post.title')).toBe('Hello')58 expect(JSONPath(data, 'post.author.name')).toBe('Superman')59 expect(JSONPath(data, 'post.author.age')).toBe(20)60 expect(JSONPath(data, 'post.tags.0')).toBe('foo')61 expect(JSONPath(data, 'post.tags[0]')).toBe('foo')62 expect(JSONPath(data, 'post.tags.1')).toBe('bar')63 expect(JSONPath(data, 'post.tags[1]')).toBe('bar')64 expect(JSONPath(data, 'post.tags.2.framework')).toBe('Hono')65 expect(JSONPath(data, 'post.tags[2].framework')).toBe('Hono')66 })6768 it('Should return undefined', () => {69 expect(JSONPath(data, 'post.foo')).toBe(undefined)70 expect(JSONPath(data, 'post.author.foo')).toBe(undefined)71 expect(JSONPath(data, 'post.tags.3')).toBe(undefined)72 expect(JSONPath(data, 'post.tags[3]')).toBe(undefined)73 })7475 it('Should return objects pointed by JSON Path', () => {76 expect(typeof JSONPath(data, 'post')).toBe('object')77 expect(JSONPath(data, 'post.author')).toEqual({ name: 'Superman', age: 20 })33 expect(JSONPath(data, 'post.tags').length).toBe(3)78 expect((JSONPath(data, 'post.tags') as JSONArray).length).toBe(3)79 })8081 it('Should return values of object as array', () => {82 expect(JSONPath(data, 'post.author[*]')).toEqual(['Superman', 20])83 })8485 it('Should return an array when targeting fields in arrays of objects', () => {86 expect(Array.isArray(JSONPath(data, 'relatedPosts[*].title'))).toBe(true)87 expect(JSONPath(data, 'relatedPosts[*].title')).toEqual([88 'HelloWorld',89 'Hello World',90 'World. Hello!',91 ])92 })9394 it('Should return all deeply nested JSON path results', () => {95 expect(Array.isArray(JSONPath(data, 'relatedPosts[*].tags[*]'))).toBe(true)96 expect(JSONPath(data, 'relatedPosts[*].tags[*]')).toEqual([97 'flash',98 'marvel',99 'spider',100 'man',101 'bat',102 'man',103 ])104 expect(JSONPath(data, 'relatedPosts[*].tags[1]')).toEqual(['marvel', 'man', 'man'])105 })106107 it('Should return only the data that exist if only some of the data have values.', () => {108 expect(JSONPath(data, 'releases[*].amd64')).toEqual([true, true])109 })110111 it('Should return undefined if there is no matching path.', () => {112 expect(JSONPath(data, 'post.category')).toEqual(undefined)113 })114115 it('Should return array of undefined if there is no matching path within array', () => {116 expect(JSONPath(data, 'releases[*].i386')).toEqual([undefined, undefined, undefined])117 })118119 it('Should return value from nested array', () => {120 expect(JSONPath(data, 'nestedArray.0.0.0')).toBe(1)121 expect(JSONPath(data, 'nestedArray[0][0][0]')).toBe(1)122 })123})
modified:src/utils/json.ts+30 added-12 removed
1export const JSONPath = (data: object, path: string) => {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 let val: any = data4 const parts = path.split('.')1export type JSONPrimitive = string | boolean | number | null | undefined2export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]3export type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject }4export type JSONValue = JSONObject | JSONArray | JSONPrimitive56const JSONPathInternal = (data: JSONValue, parts: string[]): JSONValue => {7 const length = parts.length6 for (let i = 0; i < length && val !== undefined; i++) {8 for (let i = 0; i < length && data !== undefined; i++) {9 const p = parts[i]8 if (p !== '') {9 if (typeof val === 'object') {10 val = val[p]11 } else {12 val = undefined13 }10 if (p === '') {11 continue12 }1314 if (typeof data !== 'object' || data === null) {15 return undefined16 }1718 if (p === '*') {19 const restParts = parts.slice(i + 1)20 const values = Object.values(data).map((v) => JSONPathInternal(v, restParts))21 return restParts.indexOf('*') === -1 ? values : values.flat()22 } else {23 data = (data as JSONObject)[p] // `data` may be an array, but accessing it as an object yields the same result.24 }25 }16 return val26 return data27}2829export const JSONPath = (data: JSONObject, path: string) => {30 try {31 return JSONPathInternal(data, path.replace(/\[(.*?)\]/g, '.$1').split(/\./))32 } catch (e) {33 return undefined34 }35}