JSONPath-Plus / JSONPath

A fork of JSONPath from http://goessner.net/articles/JsonPath/
Other
958 stars 169 forks source link

Undefined or null value gives error when part of an object in an array #180

Open juanreynolds opened 1 year ago

juanreynolds commented 1 year ago

Version 7.2.0 (and earlier)

This code:

import { JSONPath } from 'jsonpath-plus';

const obj = {
        arr: [
            {
                type: 'a',
            },
            {
                type: 'b',
                text: undefined as any // THIS IS THE ISSUE
            }
        ]
    }

    let val = JSONPath({
        path: JSONPath.toPathArray('$.arr[?(@.type=="b")].text'), // ISSUE HERE
        json: obj
    });

gives error: Error: jsonPath: Cannot read property 'type' of null: @.type=="b"

BUT when the 2nd item in the array has a text property that is not undefined or null it works as expected:

THIS WORKS:

const obj = {
        arr: [
            {
                type: 'a',
            },
            {
                type: 'b',
                text: 5   // THIS WORKS
            }
        ]
    }

    let val = JSONPath({
        path: JSONPath.toPathArray('$.arr[?(@.type=="b")].text'),
        json: obj
    });

AND when the path is not in array notation but in string notation it works:

THIS WORKS:

const obj = {
        arr: [
            {
                type: 'a',
            },
            {
                type: 'b',
                text: undefined as any
            }
        ]
    }

    let val = JSONPath({
        path: '$.arr[?(@.type=="b")].text',  // NOW it works
        json: obj
    });
mattweberio commented 8 months ago

We have also encountered this bug. In our schema, many values are optional and it never caused a problem with the jsonpath library. However, when using jsonpath-plus, it returns nothing if any item in the array has undefined in the chain (e.g. ".text" is undefined in one object). It would be great if this library could ignore undefined paths and still return the matches.

juanreynolds commented 6 months ago

Just tested again and the problem persists in v8.0.0. The problem only raises its head when working with array notation.