Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make string to json with javascript? (like A//a1,A//a2,A//a3//a31 ..)

Tags:

How to convert a string to JSON with javascript or jQuery? I've been thinking all day, but I do not get a good idea.

This task is to dynamically create the treeview in the client side (ASP.Net). My idea is to convert the string to an object and convert to JSON type. (String -> object -> JSON) I tried, but the day is gone. It is difficult to construct 2 more depth like A->a3->a31.

String is

var sString = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

and JSON format is

{
  "title": "A",
  "key": "1",
  "folder": true,
  "children": [{
      "title": "a1",
      "key": "2"
    }, {
      "title": "a2",
      "key": "3"
    }, {
      "title": "a3",
      "key": "4",
      "folder": true,
      "children": [{
          "title": "a31",
          "key": "5"
        }...
      }]
  }

(This is fancytreeview plugin)

‘//‘ is depth and ‘,’ is split.

Please help me..

enter image description here

Edit) I want to turn ‘sString’ to JSON format.. but It’s ok just JSON type string.

Please understand that my sentence is strange because my native language is not English.

Edit2) oh.. I want to convert the string to an object and then convert it back to JSON format. I do not have the confidence to convert that string into JSON format right away. Because there are more than 8000 variants. If It’s can, let me know how.

like image 423
cherryJang Avatar asked Dec 05 '17 11:12

cherryJang


1 Answers

I believe this can be done without recursion:

var string = "A//a1,A//a2,A//a3//a31,A//a3//a32,B,C//c1,C//c2";

// Take all the roots
var roots = string.split(',');

// We will attach it to every node and keep it incrementing
var key = 1;

// The final result will be in this object
var result = [];

// Loop through to found roots
roots.forEach(function(root) {
  // Take all the children
  var items = root.split('//');
  var parent = result;

  // Loop through the available children
  items.forEach(function(item, i) {
    // Find if the current item exists in the tree
    var child = getChild(parent, item);

    if (!child) {
    	child = {
        title: item,
        key: key++
      }
      
      // This will ensure that the current node is a folder only
      // if there are more children
      if (i < items.length - 1) {
      	child.folder = true;
        child.children = [];
      }
      
      // Attach this node to parent
      parent.push(child);
    }
    
    parent = child.children;
  });
});

console.log(result);

// Utility function to find a node in a collection of nodes by title
function getChild(parent, title) {
  for (var i = 0; i < parent.length; i++) {
    if (parent[i].title === title) {
      return parent[i];
    }
  }
}

This is the draft code which came in my mind at first. I believe it can be improved further in terms of complexity.

like image 78
31piy Avatar answered Sep 22 '22 12:09

31piy