简体   繁体   English

如何通过 JSON Object 列表检查键的值是否相等

[英]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#.我正在尝试在 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. 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.我想添加将循环遍历每个 object 的验证,并确保关键frameRate的值在数组中是相同的。

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?有一个更好的方法吗?

First of all convert your json string into JArray and use .All() to check you have same value for frameRate property of all elements.首先将您的 json 字符串转换为JArray并使用.All()检查所有元素的frameRate属性是否具有相同的值。

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 .Net 小提琴


JArray is an array of JToken , to get actual value you need to convert JToken to its actual type. JArrayJToken的数组,要获得实际值,您需要将JToken转换为其实际类型。 Here we used .Value<string>() to get value of frameRate property of JToken这里我们使用.Value<string>()来获取JTokenframeRate属性的值

You can compare all the items against the first one after parsing input to JArray and linq All method在将输入解析为JArray和 linq All方法后,您可以将所有项目与第一个项目进行比较

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. j["frameRate"]JToken的类型,这就是为什么要转换为字符串.Value<string>()在它上面调用。

Another way which is also suggested by @John: @John 也建议的另一种方式:

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

Check this fiddle - https://dotnetfiddle.net/5xOJB5检查这个小提琴 - https://dotnetfiddle.net/5xOJB5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM