Javascript 如何正确构建嵌套的 JSON 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5176433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:57:47  来源:igfitidea点击:

How do I properly structure nested JSON values?

javascriptjsondata-structures

提问by timmackay

I have a collection of JSON values that has 3 levels:

我有一组具有 3 个级别的 JSON 值:

cluster > segment > node

集群 > 段 > 节点

Where each cluster is made of segments and each segment is made up of nodes. I am trying to figure out how to represent this as a JSON object and I am unsure how to create the structure.

每个集群由段组成,每个段由节点组成。我试图弄清楚如何将其表示为 JSON 对象,但我不确定如何创建结构。

Each node contains an id and a reference to its segment id and cluster id. I have written up a test object like this:

每个节点都包含一个 id 以及对其段 id 和集群 id 的引用。我写了一个这样的测试对象:

 var customers = [
                     {
                    "cluster" : 
                         {"flights":4, "profit":5245, "clv":2364,
                    "segment" :
                        { "flights":2, "profit":2150, "clv":1564,
                            "node" :
                                    { 'xpos': 1, 'ypos': 2 }// closes node
                        }// closes segment 
                         }//closes cluster
                     },
{
                    "cluster" : 
                         {"flights":4, "profit":5245, "clv":2364,
                    "segment" :
                        { "flights":2, "profit":2150, "clv":1564,
                            "node" :
                                    { 'xpos': 1, 'ypos': 2 }// closes node
                        }// closes segment 
                         }//closes cluster
                     }
];

The part that feels a bit flaky is the way segment and node are nested. I am not getting any errors but is this the best way to represent this data?

感觉有点片状的部分是段和节点的嵌套方式。我没有收到任何错误,但这是表示这些数据的最佳方式吗?

EDIT:

编辑:

Thanks for the answers, it definitely pointed me in the right direction as far as tools to use (jsonlint) and get a better understanding of structuring data in json. They're all correct answers which shows me that it was a pretty basic question. Thanks again.

感谢您的回答,就使用工具 (jsonlint) 和更好地理解 json 中的数据结构而言,它无疑为我指明了正确的方向。他们都是正确的答案,这表明这是一个非常基本的问题。再次感谢。

回答by hvgotcodes

the nature of json you have is perfectly valid (the idea of an object nested in an object) if not syntactically correct (didn't verify that all your commas were in the right place).

如果语法不正确(未验证所有逗号都在正确的位置),则您拥有的 json 的性质是完全有效的(对象嵌套在对象中的想法)。

however, you dont have what you said you wanted, which is a collectionof segments in a cluster, and a collection of nodes in a segment.

但是,你没有你说什么你想要的,这是一个集群中的片段,和节点的一个段的集合。

change it to be

把它改成

[{
  "cluster": {..,
     "segments": [{    <--- note the array -- you now have a collection
         "name": 'segment1', <- optional, just here to show multiple segments
         "nodes": [{....}] <-- same here
     }, 
     {
         "name": 'segment2',
         "nodes": [{....}]
     }]
  }
}]

回答by no.good.at.coding

I think this looks alright for the most part. However, note the following:

我认为这在大多数情况下看起来不错。但是,请注意以下几点:

  1. JSON key and values should be in double quotes"and not single quotes'. Look at yourxposandypos` values to see what I mean. I usually use JSONLintto ensure that my JSON is valid.

  2. You say that clusters have a collection of segments and segments have a collection of nodes. This might be best represented as arrays.

  3. It also looks like you want multiple clusters. That is also best expressed as an array.

  1. JSON key and values should be in double quotes" and not single quotes' . Look at yourxpos andypos` 值来看看我的意思。我通常使用JSONLint来确保我的 JSON 是有效的。

  2. 你说cluster■找集合segmentS和segment■找集合node秒。这可能最好表示为数组。

  3. 看起来您还需要多个集群。这也最好表示为数组。

So something of the form (greatly exaggerated the indentation, hopefully that will help):

所以一些形式(大大夸大了缩进,希望这会有所帮助):

{
    "cluster" : [
                    {
                        "flights": 4,
                        "profit": 5245,
                        "clv": 2364,
                        "segment" : [
                                        {
                                            "flights": 2,
                                            "profit": 2150,
                                            "clv": 1564,
                                            "node" : [
                                                        {
                                                            "xpos": 1,
                                                            "ypos": 2 
                                                        }, 
                                                        {
                                                            //node 2
                                                        }
                                                    ] 
                                        }, 
                                        {
                                            //segment 2
                                        }
                                    ] 
                    },
                    {
                        //next cluster
                    }
                ]
}

回答by Anurag

There is nothing wrong with the nesting, however, if each cluster can contain multiple segments, and each segment can in-turn have multiple nodes, then you ought to use an array.

嵌套没有问题,但是,如果每个集群可以包含多个段,并且每个段又可以有多个节点,那么您应该使用数组。

{
    "cluster": {
        "flights": 4,
        ...,
        "segments": [ // segments is an array
            { 
                "flights": 6,
                "nodes": [ // nodes is an array
                    { "xpos": 4, "ypos": 6 },
                    { "xpos": 1, "ypos": 6 },
                    { third node },
                    ...
                ]
            },
            { second segment },
            ...
        ]
    }
}

回答by iivel

Seems fine to me, though out of habit I check everything in http://www.jsonlint.comand the slightly 'fixed' version validates (remove your single quotes and ensure you name the structure):

对我来说似乎很好,但出于习惯,我检查了http://www.jsonlint.com 中的所有内容,并且稍微“固定”的版本验证(删除单引号并确保为结构命名):

{
    "customers": [
        {
            "cluster" : {
                "flights": 4,
                "profit": 5245,
                "clv": 2364,
                "segment" : {
                    "flights": 2,
                    "profit": 2150,
                    "clv": 1564,
                    "node" : {
                        "xpos": 1,
                        "ypos": 2 
                    } 
                } 
            } 
        },
        {
            "cluster" : {
                "flights": 4,
                "profit": 5245,
                "clv": 2364,
                "segment" : {
                    "flights": 2,
                    "profit": 2150,
                    "clv": 1564,
                    "node" : {
                        "xpos": 1,
                        "ypos": 2 
                    } 
                } 
            } 
        } 
    ]
}

As a note, if you were to let jQuery or another plugin do the 'JSONification' it would turn out the same, as has also been noted, you're not representing the segments, etc as a collection (this is where I personally find building the object to be an easier representation).

需要注意的是,如果您让 jQuery 或其他插件执行“JSONification”,结果会是一样的,正如也已经指出的那样,您没有将段等表示为一个集合(这是我个人发现的将对象构建为更简单的表示)。

.. ala (but build your object out):

.. ala(但构建您的对象):


var stuff = {};
stuff.customers = [];
stuff.customers[stuff.customers.length] = new Cluster();
stuff.customers[i].segment[stuff.customers[i].segment.length] = new Segment();

...etc.
...blah blah fill out object

$.toJSON('{"customerArrary":' + stuff + '}');

function cluster(){
  this.flights;
  this.profit;
  this.clv;
  this.segment = [];
}

function Segment(){
  this.flights;
  this.profit;
  this.clv;
  this.node = [];
}

function Node(){
  this.xpos;
  this.ypos;
}

回答by Kay V

Here's an improvement to the logic with no loss of meaning:

这是对逻辑的改进,但没有失去意义:

var customers = [
                  {
                    "ID" : "client ABC",
                    "cluster" : { "ID": "cluster 123", "flights": 4, "profit": 5245, "clv": 2364 },
                    "segment" : { "ID": "segment 456", "flights": 2, "profit": 2150, "clv": 1564 },
                    "node" : { "xpos" : 1, "ypos" : 2 }
                  }, {
                    "ID" : "client DEF",
                    "cluster" : { "ID": "cluster 789", "flights": 4, "profit": 5245, "clv": 2364 },
                    "segment" : { "ID": "segment 876", "flights": 2, "profit": 2150, "clv": 1564 },
                    "node" : { "xpos" : 1, "ypos" : 2 }
                  }
];

In the above, the actual 'levels' are

在上面,实际的“级别”是

clusters > flights etc & segments > flights etc & nodes > xpos etc

which could also be written:

也可以写成:

level 1: clusters
  level 2: flights, profit, & clv (note: values are unique from segments tho labels are identical)

level 1: segments
  level 2: flights, profit, & clv

level 1: nodes
  level 2: xpos & ypos

Ok, let's agree the OP's example (as initially written) can meet the strict mechanical requirements of the JSON spec.

好的,让我们同意 OP 的示例(如最初编写的那样)可以满足 JSON 规范的严格机械要求。

However, the OP describes 3 'levels', illustrating them as cluster > segment > node. The word 'level' and the arrows only make any sense if there is a semantic relationship between those objects. After all, 'levels' must relate to each other in a hierarchy, inheritance, sequence or some similarly layered fashion.

但是,OP 描述了 3 个“级别”,将它们说明为集群 > 段 > 节点。如果这些对象之间存在语义关系,则“级别”一词和箭头才有意义。毕竟,“级别”必须以层次结构、继承、顺序或某种类似的分层方式相互关联。

The original example gives no hint of the relationship between any part of a cluster and any part of a segment or any part of a node; it gives no way to guess what the relationship should be. The labels just sit adjacent to each other in the example, with a few extraneous braces around them.

最初的例子没有提示集群的任何部分与段的任何部分或节点的任何部分之间的关​​系;它无法猜测这种关系应该是什么。在示例中,标签只是彼此相邻,周围有一些无关紧要的括号。

Without an apparent relationship to encode, each of these keys most logically names a unique property of a 'customer' object--that is to say, each customer has clusters, segments and nodes. Each property is clearly labeled, and each can happily coexist in a flat structure. If OP has more info on relationships that require levels, the structure is easy to modify.

如果没有明显的编码关系,这些键中的每一个都最合乎逻辑地命名了“客户”对象的唯一属性——也就是说,每个客户都有集群、段和节点。每个属性都有明确的标签,每个属性都可以在一个平面结构中愉快地共存。如果 OP 有更多关于需要级别的关系的信息,则结构很容易修改。

In short, nesting should have a semantic purpose; if it does not, markers of nesting should be omitted. As presented, much of the JSON syntax in the OP's example had no apparent meaning and introduces logical issues. The revision resolves these issues as well as possible with given information.

总之,嵌套应该有语义目的;如果不是,则应省略嵌套标记。如上所述,OP 示例中的大部分 JSON 语法都没有明显的意义并引入了逻辑问题。修订版使用给定的信息尽可能地解决了这些问题。