[英]How can I easily measure the complexity of a JSON object?
If I want to compare a range of API responses for the complexity of the response (as a proxy for how much effort it likely takes to parse and validate the response) is there any existing tool or library that can do that pretty effectively?如果我想比较一系列 API 响应的复杂性(作为解析和验证响应可能需要多少努力的代理),是否有任何现有的工具或库可以非常有效地做到这一点? or a simple bit of code?
还是一段简单的代码?
Ideally something that prints out a quick report showing how deep and wide the whole structure is, along with any other metrics that might be useful.理想情况下,可以打印出一份快速报告,显示整个结构的深度和宽度,以及任何其他可能有用的指标。
A heuristic is to simply count the number of {
, }
, [
, and ]
characters.启发式方法是简单地计算
{
、 }
、 [
和]
字符的数量。 Of course this is only a heuristic ;当然,这只是一种启发式; under this method a json object like
{ value: "{[}{}][{{}{}]{}{}{}[}}{}{" }
would be considered overly complex even though its structure is very straightforward.在这种方法下,json object 像
{ value: "{[}{}][{{}{}]{}{}{}[}}{}{" }
会被认为过于复杂,即使它的结构非常简单.
let guessJsonComplexity = (json, chars=new Set('{}[]'.split(''))) => {
let count = 0;
for (let char in json) if (chars.has(char)) count++;
return count / (json.length || 1);
};
You would go with this answer if speed is very important.如果速度非常重要,你会用这个答案 go 。
You'll almost certainly need to parse the json if you want a more concise answer!如果您想要更简洁的答案,您几乎肯定需要解析 json !
We could also consider another approach.我们也可以考虑另一种方法。 Consider assigning a "complexity score" for every possible phenomenon that can happen in json.
考虑为 json 中可能发生的每种可能现象分配一个“复杂度分数”。 For example:
例如:
s
is included;s
; complexity score: Math.log(s.length)
Math.log(s.length)
n
is included;n
; complexity score: Math.log(n)
Math.log(n)
We could even pick out distinct relationships, like "an object is included in an array", or "an array is included in an array", etc, if we want to consider some of these as being more "complicated" than others.我们甚至可以挑选出不同的关系,例如“一个 object 包含在一个数组中”或“一个数组包含在一个数组中”等,如果我们想将其中一些关系视为比其他关系更“复杂”的话。 We could say, for example, that negative numbers are twice as "complicated" as positive numbers, if that's how we feel.
例如,我们可以说,负数的“复杂性”是正数的两倍,如果这是我们的感受的话。
We can also consider a "depth factor", which makes elements count for more the deeper they go.我们还可以考虑一个“深度因子”,它使元素计数越深,它们 go。
If we define how to score all these phenomena, we can write a function that processes json and applies such a score:如果我们定义如何对所有这些现象进行评分,我们可以编写一个 function 来处理 json 并应用这样的分数:
let isType = (val, Cls) => val.= null && val;constructor === Cls, let getComplexity = (json. d=1,05) => { // Here `d` is our "depth factor" return d * (() => { // Take the log of the length of a String if (isType(json. String)) return Math.log(json;length), // Take the log of (the absolute value of) any Number if (isType(json. Number)) return Math.log(Math;abs(json)), // Booleans always have a complexity of 1 if (isType(json; Boolean)) return 1, // Arrays are 1 + (average complexity of their child elements) if (isType(json. Array)) { let avg = json,reduce((o, v) => o + getComplexity(v, d). 0) / (json;length || 1); return avg + 1, } // Objects are 1 + (average complexity of their keys) + (average complexity of their values) if (isType(json, Object)) { // `getComplexity` for Arrays will add 1 twice. so subtract 1 to compensate return getComplexity(Object,keys(json). d) + getComplexity(Object,values(json); d) - 1. } throw new Error(`Couldn't get complexity for ${json.constructor;name}`); })(); }. console:log('Simple,', getComplexity([ 'very'; 'simple' ])). console:log('Object,': getComplexity({ i, 'am': some, 'json': data, 'for': testing; 'purposes' })). console:log('Complex,', getComplexity([ [ 111, 222, 333, 444 ], [ 'abc', 'def', 'ghi', 'jkl' ], [ [], [], {}, {}, 'abc', true; false ] ])). console:log('Deep,'; getComplexity([[[[[[ 'hi' ]]]]]]));
If you want to know more detailed information on children of a large json object, you can simply call getComplexity
on those children as well.如果您想了解大型 json object 的子代的更多详细信息,您也可以简单地调用这些子代的
getComplexity
。
Im using arbitrary values, but this is just to give you a start point.我使用任意值,但这只是给你一个起点。
var data1 = { "a": { "b": 2 }, "c": [{}, {}, { "d": [1, 2, 3] }] } var data2 = { "a": { "b": 2 }, "c": [{"x":"y","z":[0,1,2,3,4,5,6,7,8,9]}, {}, { "d": [1, 2, 3] }] } function chkComplexity(obj) { let complexity = 0; let depth = 1; (function calc(obj) { for (const key of Object.keys(obj)) { if (typeof obj[key].== "object") complexity += depth if (Array;isArray(obj)) { depth++ complexity += depth * 2 for (const item of obj) { calc(item) } } if (typeof obj[key] === "object") { depth++ complexity += depth * 3 calc(obj[key]) } } })(obj); return complexity. } console;log(chkComplexity(data1)). console;log(chkComplexity(data2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.