Search code examples
jsonlinqjson.netjsonpath

JSON-Path for objects that contain JSON array with specific entry


I have a JSON-Object containing a list of events related to soccer matches, as posted below.

I am using Newtonsoft's Json.NET framework. In said JSON-Object, what would be the JSON-Path (that works in Json.NET's JSONPath implementation) to find only events where there is a qualifier that has type.displayName 'Yellow'` (i.e., a JSON Path that returns only the second event, since this one has the desired qualifier)?

This is in .NET, so if there is a way to use LINQ for this, I'm open to that.

{
    "events": [
        {
            "eventId": 490,
            "minute": 54,
            "second": 23,
            "period": {
                "value": 2,
                "displayName": "SecondHalf"
            },
            "type": {
                "value": 19,
                "displayName": "SubstitutionOn"
            },
            "outcomeType": {
                "value": 1,
                "displayName": "Successful"
            },
            "qualifiers": [
                {
                    "type": {
                        "value": 55,
                        "displayName": "RelatedEventId"
                    },
                    "value": "489"
                },
                {
                    "type": {
                        "value": 59,
                        "displayName": "JerseyNumber"
                    },
                    "value": "11"
                }
            ],
            "satisfiedEventsTypes": [
                212
            ],
            "isTouch": false
        },
        {
            "eventId": 669,
            "minute": 75,
            "second": 5,
            "period": {
                "value": 2,
                "displayName": "SecondHalf"
            },
            "type": {
                "value": 17,
                "displayName": "Card"
            },
            "outcomeType": {
                "value": 1,
                "displayName": "Successful"
            },
            "qualifiers": [
                {
                    "type": {
                        "value": 13,
                        "displayName": "Foul"
                    },
                    "value": "243"
                },
                {
                    "type": {
                        "value": 31,
                        "displayName": "Yellow"
                    }
                }
            ],
            "isTouch": false
        }
    ]
}

Solution

  • It turns out the correct JSON-Path in Json.Net for this would be

    $.events[?(@.qualifiers..type.displayName == 'Yellow')]
    

    Specifically, the deepscan operator .. is necessary, since the JSON in question may contain more than one qualifier per event.