简体   繁体   English

创建多级JSON字符串

[英]Creation of a multi-level JSON string

I want to create a multi-level JSON string with JS. 我想用JS创建一个多级JSON字符串。

Scenario 脚本

3 countries with 5 grandfathers with 3 kids which whom also have 3 kids that have 5 friends. 3个国家/地区,有5个祖父和3个孩子,其中3个孩子有5个朋友。

I get the data from a external JSON file that looks like this. 我从看起来像这样的外部JSON文件中获取数据。

 {"countries":[
    {
        "name":"USA",

        "grandfathers":[
            {
                "gFName":"Steve",
                "grandfathersKid":[
                    {
                        "gFKName": "Linda",
                        "kid": [{
                            "name": "Steve JR", 
                            "friends": [{
                                "name": "Kriss|John|Martin|Steven"
                            }]
                        }
                        ]
                    }

                ]
            }
        ]
    }
]}

And now I want to store some of the countries with people and their relatives and friends in aa new JSON list that looks exactly as the list made in the external json file. 现在,我想将与人及其亲戚和朋友一起的一些国家/地区存储在一个新的JSON列表中,该列表与外部json文件中的列表完全一样。 I aim to use this "homemade" list later on in the script. 我的目标是稍后在脚本中使用此“自制”列表。

My initial response for this was 我对此的最初回应是

var tree = new Array();

tree = {};


var countries = new Array();

countries[0] = "canada";
countries[1] = "USA";
countries[2] = "Mexico";
countries[0][0] = "Steve"; //Lives in Canada
countries[0][0][0] = "Linda"; //Daughter of Steve
countries[0][0][0][0] = "Steve JR"; // Kid of Linda
countries[0][0][0][0][0] = "Kriss"; //Steves Friend
...


$.each(countries...function(index, value){
      tree[index].country = value;

  $.each(grandfathers...function(key, value){
      tree[index].country[key].grandfather = value;

}

And so on, but this is not giving me the result I want. 依此类推,但这并没有给我想要的结果。 What am I doing wrong? 我究竟做错了什么? And a more effective way than to take each of everything? 还有比拿走所有东西更有效的方法吗?

Third edit... 第三编辑...

Is this the sort of thing you're trying to do? 这是您要尝试做的事情吗?

var countries = $.map(oldCountries || [], function(country) {
    return {
        name: country.name,
        people: $.map(country.grandfathers || [], function(gpa) {
            return {
                name: gpa.gFName,
                children: $.map(gpa.grandfathersKid || [], function(parent) {
                    return {
                        name: parent.gFKName,
                        children: $.map(parent.kid || [], function(kid) {
                            return {
                                name: kid.name,
                                friends: kid.friends
                            };
                        })
                    };
                })
            };
        })
    };
});

I wasn't sure what to do with the friends node. 我不确定该如何处理friends节点。 Should that be normalized into something more useful, or do you want to leave it alone? 应该将其标准化为更有用的东西,还是想让它一个人呆着?

This Fiddle demonstrates the technique. 小提琴演示了该技术。

I think we'd need to know more about your requirements. 我认为我们需要更多地了解您的要求。 But several thing I see here are: 但是我在这里看到的几件事是:

  • You declare tree and initialize it as an Array, then immediately reinitialize it as an 您声明树并将其初始化为Array,然后立即将其重新初始化为
    empty object 空物体
  • You are not creating the intermediate nodes here, such as tree[index] but just assuming that they exist. 您不是在这里创建中间节点,例如tree[index]而是假设它们存在。
  • You are trying to assign the country[key] property of an object, using the dot-property access. 您正在尝试使用点属性访问来分配对象的country[key]属性。

Can you supply the countries structure and the grandfather's structure. 您能提供国家结构和祖父结构吗? And are they nested? 并且它们嵌套吗?

And finally, what would you like for the output format? 最后,您想要什么输出格式? The code above hints at it, but it's still a little fuzzy. 上面的代码暗示了这一点,但是仍然有些模糊。

Edit 编辑

So are you trying to achieve a structure something like this?: 那么,您是否要实现这样的结构?:

var countries = [
  {
     name: "Canada",
     people: [
       {
          name: "Steve",
          children: [
            {
               name: "Linda",
               children: [
                 {
                    name: "Steve, Jr.",
                    friends: [
                      {
                         name: "Kriss"
                      }
                      //, more friends
                    ]
                 }
                 //, more grandchildren
               ]
            }
            //, more parents
          ]
       }
       //, more grandparents
     ]
   }
   //, more countries
 ];

May be this jsfiddle can help you to get started? 也许这个jsfiddle可以帮助您入门吗?
And here is an example derived from your code. 这是从您的代码派生的示例

Sounds like a homework, so I'll try to point you in the right direction. 听起来像是一项作业,所以我会尝试为您指明正确的方向。 I think you are confusing objects and arrays. 我认为您在混淆对象和数组。 You could use a "country" object and a "person" object. 您可以使用“国家”对象和“人”对象。 A country object should have an array of person objects, as inhabitants. 国家对象应具有一系列人对象,例如居民。 Person objects can have an array of person objects as descendants. 人员对象可以具有一组人员对象作为后代。 Add a method like "addDescendant", which creates a new person under a person. 添加诸如“ addDescendant”之类的方法,该方法可在人员下创建一个新人员。 From There you can build the structure as you like. 从那里您可以根据需要构建结构。 Here is some pseudo code: 这是一些伪代码:

countries = [];
function Country(name){ this.name = name; this.population = [];}
function Person(kids){this.descendants = []; this.addDescendant = function(){...}; 
    //loop from 1 to kids and add descendants as "new Person"
}
person = new Person(3);
country1 = new Country("MyCountry1");
// now add people to country1.population
countries.push(country1);

The final structure should look something like this: 最终结构应如下所示:

countries = [
    { name: "country 1",
      people: [{ name: "Steve"}, 
               {name: "Clara", descendants: [{name: "Clara's daughter"}, 
                                             {name: "Clara's son"}]
              ]}
    },
    { name: "country 2",
      people: [{}, {} ...]

    }
];

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

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