简体   繁体   中英

How to form a nested JSON object from an array?

I have a path(as a string) like

A/B/C/D

. I want to represent it as a JSON object as follows :

{
   A:{
      B:{
         C:D
      }
   }
}

Now lets say I add a path

A/B/C/X

then the JSON should look like

{
   A:{
      B:{
         C:[D,X]
      }
   }
}

So what I do is when I get the path, I split it and store in an array as follows

var struct = {};
var path = $scope.path.split("/"); //assuming $scope.path holds the path  
for(var i =0;i<path.length-1;i++)
    {
        struct[path[i]] = path[i+1];
    }

However this leads to json as {A: "B", B: "C", C: "D"} . How do I fix this? Is there a recursive way to do this?

EDIT : My previous schema would lead to error. As KevinB suggested, I am updating the schema to something like [{name: 'A', children: [{name: 'B', children: []}]}]

Yes, take a look at this function which was created for that (i'm the author, by the way):

https://github.com/DiegoZoracKy/make-object-path

The code is:

    var makeObjectPath = function(_src, _path, _val) {

    var src = _src,
        path = _path,
        val = _val;

    if (arguments[0] instanceof Array || typeof(arguments[0]) == 'string') {
        src = {};
        path = arguments[0];
        val = arguments[1] || null;
    }

    path = (typeof(path) == 'string') ? path.split('.') : path;

    var o = src;
    var currentO = o;
    for (var i in path) {
        currentO[path[i]] = (i != path.length - 1) ? currentO[path[i]] || {} : (val) ? val : {};
        currentO = currentO[path[i]];
    }
    return o;
} 

And to use it:

makeObjectPath('root.parent.child', 'someValue');

// Output:

{
    "root":{
        "parent":{
            "child":"someValue"
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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