简体   繁体   English

JSON 到 Javascript 中的父/子对象

[英]JSON to Parent/child object in Javascript

I'm currently trying to display Json data into a Material Tree , the problem is that the material tree won't directly take a Json dataSource and i need to convert mine to something like this :我目前正在尝试将 Json 数据显示到Material Tree 中,问题是材质树不会直接采用 Json 数据源,我需要将我的数据转换为这样的:

[
  {
    name: 'Fruit',
    children: [
      {name: 'Apple'},
      {name: 'Banana'},
      {name: 'Fruit loops'},
    ]
  }, {
    name: 'Vegetables',
    children: [
      {
        name: 'Green',
        children: [
          {name: 'Broccoli'},
          {name: 'Brussel sprouts'},
        ]
      }
    ]
  },
];

The json data look like this : json 数据如下所示:

{
    "processTimer": {
        "Environment": {
            "Environment": {
                "initiator": {
                    "commonName": "anonymous"
                },
                "locale": "fr_FR",
                "counter": "9004",
                "last-fault": {
                    "type": "FaultException",
                    "message": "java.lang.NullPointerException",

                }
            }
        }
    {"oui" : {
       "_uri": "",
       "__text" : ""
      }
   }
    }
}

After weeks of search i understood that i would need a recursive function that take incoming json and traverse it throught to rebuild the new object.经过数周的搜索,我明白我需要一个递归函数来获取传入的 json 并遍历它以重建新对象。 But i don't really get how do i get all the keys and transform them into values.但是我真的不知道如何获取所有键并将它们转换为值。 I tried a lot of different StackOverflow code but i couldn't find one that does what i need.我尝试了很多不同的 StackOverflow 代码,但找不到满足我需要的代码。

I reseigned on using ngx-json-viewer for now even tho it's not the sexiest it takes directly json format in, i still wonder why most of the javascript Tree libraries don't.我现在重新使用ngx-json-viewer ,即使它不是最性感的直接使用 json 格式,我仍然想知道为什么大多数 javascript Tree 库没有。

If someone found something or want to give me a hand it would be greatly appreciated.如果有人发现了什么或想帮我一把,我将不胜感激。

Thanks in advance !提前致谢 ! :) :)

Edit: i Found this method on this thread that help me to navigate the object :编辑:我在这个线程上找到了这个方法来帮助我导航对象:

traverse(jsonObj) {

    if (jsonObj !== null && typeof jsonObj == "object") {

      Object.entries(jsonObj).forEach(([key, value]) => {

        // If value is an object (This means that the value is a child) and is the same as a variable 
        //(because the first key is always the processName)
        if (typeof value == "object" && key == this.processName) {
          this.treeObject.push({ name: key, children: [] })
          this.traverse(value)

          //If value is an object (This means that the value is a child)
        } else if (typeof value == "object") {
          this.treeObject[0].children.push({ name: key, children: [] })
          this.traverse(value)

          // If value is a real value
        } else if (typeof value != "object") {
          this.treeObject[0].children.push({ name: key, value: value })
        }
      });
    }
  }

The problem is that i don't know how to go deeper into the TreeObject at the same time as i'm going deeper in the JsonObj, how to keep track of the level, because right now it obviously push each item in the first array after the processName like this :问题是我不知道如何在深入了解 JsonObj 的同时更深入地了解 TreeObject,如何跟踪级别,因为现在它显然将每个项目推送到第一个数组中在像这样的 processName 之后:

[{…}]
0: name: "ProcessTimer"
children: Array(25)
0: {name: "Environment", children: Array(0)}
1: {name: "_uri", children: Array(1)}
2: {name: "Environment", children: Array(0)}
...
...
23: {name: "_uri", children: Array(1)}
24: {name: "__text", children: Array(1)}

Thanks for any help !谢谢你的帮助 !

I finally managed to do it with the JSON that i got from the server, it had to be parsed with JSON.parse and then sent to this method buildTree() that the material team gives us我终于设法使用从服务器获得的 JSON 来完成它,必须使用 JSON.parse 对其进行解析,然后将其发送到材质团队提供给我们的 buildTree() 方法

ngOnInit(){
const dataObject = JSON.parse(jsonMessage);
const data = this.buildFileTree(dataObject, 0);
}

buildFileTree(obj: { [key: string]: any }, level: number): FileNode[] {
    return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
      const value = obj[key];
      const node = new FileNode();
      node.name = key;
      if (value != null) {
        if (typeof value === 'object') {
          node.children = this.buildFileTree(value, level + 1);
        } else {
          node.type = value;
        }
      }
      return accumulator.concat(node);
    }, []);
  }

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

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