curious_debugger
curious_debugger

Reputation: 329

How to check if the value of a key is equal through out the list of JSON Object

I am trying input some validation in C#. I have a LIST of JSON Object, and I want to add a validation that will check for a value of certain key and make sure they are all same in all the JSON object in the array.

LIST -

subtitles = [{ frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '23', dropFrame: False}]

I want to add validation that will loop through every object and make sure that the value of the key frameRate is same through the array.

This is what i tried to do - I created a aempty list and then tried to push all the frameRates and then looped through it and compared the value with previous one.

List<string> subtitleSegmentsFrameRates = new List<string>();

            foreach (var subtitle in segmentSubtitles) 
            {
                subtitleSegmentsFrameRates.Add(subtitle.frameRate);
                    
            }

            for (int i = 0; i < subtitleSegmentsFrameRates.Count; i++) {
                if (i != 0) {
                    if (subtitleSegmentsFrameRates[i] != subtitleSegmentsFrameRates[i - 1]) {
                        throw new CustomException("Frame Rates arocss segments do not match.");
                    }
                }
            }

Is there a better way to do this ?

Upvotes: 0

Views: 1209

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

First of all convert your json string into JArray and use .All() to check you have same value for frameRate property of all elements.

using System;
using Newtonsoft.Json.Linq;
using System.Linq;

...
var validFrameRate = JArray.Parse(subtitles)  //Convert an Sub titles to JArray
           .All(x => x.Value<string>("frameRate") == "25");  //Check all frame rates are same or not.

Console.WriteLine(validFrameRate ? "Same frameRate in all elements" : "Different FrameRate in all elements");

.Net Fiddle


JArray is an array of JToken, to get actual value you need to convert JToken to its actual type. Here we used .Value<string>() to get value of frameRate property of JToken

Upvotes: 1

user1672994
user1672994

Reputation: 10849

You can compare all the items against the first one after parsing input to JArray and linq All method

var jArray = JArray.Parse(subtitles);
bool allSame = jArray.All(j => j["frameRate"].Value<string>() == jArray[0]["frameRate"].Value<string>());

j["frameRate"] is type of JToken that's why to convert to string .Value<string>() is invoked over it.

Another way which is also suggested by @John:

bool same = jArray.Select(j => j["frameRate"].Value<string>()).Distinct().Count() == 1

Check this fiddle - https://dotnetfiddle.net/5xOJB5

Upvotes: 1

Related Questions