【发布时间】:2018-04-07 05:30:26
【问题描述】:
我有如下 URL 列表。如何将其转换为完整的 json 对象?
我的 URL 数组。
[
"path1/subpath1/file1.doc","path1/subpath1/file2.doc","path1/subpath2/file1.doc","path1/subpath2/file2.doc","path2/subpath1/file1.doc","path2/subpath1/file2.doc","path2/subpath2/file1.doc","path2/subpath2/file2.doc","path2/subpath2/additionalpath1/file1.doc"
]
我希望这是一个 json 对象,例如:
{
"path1":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"]
},
"path2":{
"subpath1":["file1.doc","file2.doc"],
"subpath2":["file1.doc","file2.doc"],
"additionalpath1":{
"additionalpath1":["file1.doc"]
}
}
}
如何做到这一点?
我用下面的代码 sn-ps 试过了。但是缺少几个文件夹对象。
如果您尝试此代码,您会发现缺少test1 和其他objects:
<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p id="demo"></p>
<script>
let paths = [ "admin/640954.jpg", "admin/test1/3m-nd.jpg",
"admin/test1/Acct.png", "admin/test1/additional/111.gif", "admin/test1/additional/Aard.jpg",
"dp/151292.jpg", "dp/151269.jpg", "dp/1515991.jpg" ];
function getMap(urls){
var map = {};
urls.forEach(function(url){
var parts = url.split("/");
makePath(map, parts);
})
return map;
}
function makePath(map,parts){
var currentPath = map;
for(var i = 0 ; i < parts.length - 1 ; i++ ){
if(i == parts.length -2 ){
currentPath[parts[i]] = currentPath[parts[i]] || [];
currentPath[parts[i]].push(parts[++i]);
}else{
currentPath[parts[i]] = currentPath[parts[i]] || {};
currentPath = currentPath[parts[i]];
}
}
}
document.getElementById("demo").innerHTML=JSON.stringify(getMap(paths));
</script>
</body>
</html>
【问题讨论】:
-
您可以使用递归映射算法来做到这一点。
-
您使用哪种语言编写代码?
-
@MohitMutha 看看标签。
-
你可以在最后一个正斜杠之后抓取所有内容。你已经尝试过什么?
标签: javascript jquery json