简体   繁体   English

如何轻松测量 JSON object 的复杂性?

[英]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:例如:

  • A string s is included;包含一个字符串s complexity score: Math.log(s.length)复杂度得分: Math.log(s.length)
  • A number n is included;包括一个数字n complexity score: Math.log(n)复杂度得分: Math.log(n)
  • A boolean is included;包括一个 boolean; complexity score: 1复杂度得分:1
  • An array is included;包含一个数组; complexity score: average complexity of elements + 1复杂度分数:元素的平均复杂度 + 1
  • An object is included;包括一个 object; complexity score: average complexity of values plus average complexity of keys + 1复杂度分数:值的平均复杂度加上键的平均复杂度 + 1

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.

相关问题 如何轻松地将外部连接的 SQL 表转换为 json 对象? - How can I easily convert an outer joined SQL table to a json object? 如何在HTML / JavaScript中轻松处理JSON重定向? - How can I easily handle redirects by JSON in HTML/JavaScript? 是否可以返回 json_encode() 但作为数组而不是对象,所以我可以轻松使用 `.filter()` 或 `.forEach()` 方法 - Is it possible to return json_encode() but as an array and not an object, so I can use `.filter()` or `.forEach()` methods easily 如何从TypeScript中的匿名对象轻松创建强类型对象? - How can I easily create a strongly typed object from an anonymous object in TypeScript? 我如何轻松地使用JavaScript函数从json字符串中解析出特定对象 - How can I easily have a javascript function to parse out specific objects from json string 我怎样才能最容易地将这个 HTTP 响应解析为 JSON 然后访问 responseText 字段? - How can I most easily parse this HTTP response into JSON to then access responseText fields? 如何轻松访问文件夹的图片? - How can I easily access the pictures of a folder? 如何轻松执行JavaScript文件? - How can I execute a JavaScript file easily? 如何轻松制作新数组? - How can i make a new array easily? 如何轻松禁用fancybox幻灯片显示? - How can I easily disable fancybox slideshow?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM