2016-07-30 7 views
0

Kann jemand mich auf einen richtigen Ansatz verweisen? Muss ich nach dem Parsen der Eingabe zuerst einen Baum erstellen und ihn dann umwandeln?Build-JSON-String von repräsentativen Eingabe

die Eingabe erfolgt in folgenden Form gegeben:

node11/node12/.../node1k 
node21/node22/.../node2n 
... 
nodem1/nodem2/.../nodeml 

Probeneingang:

a/b/c1 
x/b 
a/b/c/d 
m 

Ausgang:

{ 
    a: { 
    b: { 
     c: { d: "" }, 
     c1: "" 
     } 
     }, 
    x: { b: "" }, 
    m: "" 
} 

Antwort

1

Hier ist eine JS-Lösung, die Rekursion verwendet, um jeden Pfad zu verarbeiten.

function parse(paths) { 
 
    var resultObj = {}; 
 
    paths.forEach(function(path) { 
 
    var nodes = path.split("/"); 
 
    recurse(nodes, resultObj); 
 
    }); 
 
    console.log(resultObj); 
 
    console.log(JSON.stringify(resultObj)); 
 
} 
 

 
function recurse(path, obj) { 
 
    if (!path.length) 
 
    return obj; 
 
    var node = path.shift(); 
 
    if (!obj.hasOwnProperty(node)) 
 
    obj[node] = path.length ? {} : ""; 
 
    return recurse(path, obj[node]); 
 
} 
 

 
var arr = ["a/b/c1", "x/b", "a/b/c/d", "m"]; 
 
parse(arr);

1

Wenn Sie dies in Python tun mögen, können Sie könnte dies tun:

output = {} 
lines = ["a/b/c1", "x/b", "a/b/c/d", "m"] 
for line in lines: 
    nodePath = line.split('/') 
    current = output 
    for node in nodePath[:-1]: 
     current[node] = {} if node not in current else current[node] 
     current = current[node] 
    current[nodePath[-1]] = "" 

print output # gives us {'a': {'b': {'c1': '', 'c': {'d': ''}}}, 'x': {'b': ''}, 'm': ''} 

Dann drehen Sie den Ausgang in json, wie Sie wollen.