现有数据:
string[] list = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
...
];
需要按":"符号分割成如下格式的JSON
[
{
"name": "a1",
"child": [
{
"name": "b1",
"child": [
{
"name": "c1",
"child": []
}
]
},
{
"name": "b2",
"child": [
{
"name": "c2",
"child": [
{
"name": "d1",
"child": []
},
{
"name": "d2",
"child": []
}
]
}
]
}
]
}
]
求大神支招。。。
[Test]
public void Test1()
{
var dataList = new[] {"a1:b1:c1", "a1:b2:c2:d1:", "a2:b2:c2:d2"};
var root = new List<dynamic>();
var dict = new Dictionary<string, dynamic>();//字典,方便搜索node
foreach (var data in dataList)
{
dynamic parent = null;
foreach (var name in data.Split(':'))
{
dict.TryGetValue(name, out var current);
if (current != null)
{
parent = current;
continue;
}
var node = new {name, child = new List<dynamic>()};
if (parent == null)
{
root.Add(node);
}
else
{
parent.child.Add(node);
}
parent = node;
dict.Add(name, node);
}
}
Console.WriteLine(DefaultJsonSerializer.Instance.SerializeObject(root));
}
[{"name":"a1", "child":[{"name":"b1", "child":[{"name":"c1", "child":[]}]},{"name":"b2", "child":[{"name":"c2", "child":[{"name":"d1", "child":[{"name":"", "child":[]}]},{"name":"d2", "child":[]}]}]}]},{"name":"a2", "child":[]}]
lis = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
]
new_lis =[]
for str in lis:
str_lis = str.split(':')
dic ={}
start_index = 0
def func(dic,start_index):
if start_index==len(str_lis):return
dic['name']= str_lis[start_index]
start_index+=1
dic ['child']={}
func(dic['child'],start_index)
func(dic,start_index)
new_lis.append(dic)
print(new_lis)
@小小咸鱼YwY: 大兄弟,这是啥语法啊。。c#怎么写?
@翩若游龙: python,你只要用递归的思想就可以了,蛮简单的
@翩若游龙:
lis = [
"a1:b1:c1",
"a1:b2:c2:d1:",
"a2:b2:c2:d2"
]
new_lis =[]
for str in lis:
str_lis = str.split(':') #首先肯定切分
start_index = 0
def func(lis,start_index): #导入一个空列表
if start_index==len(str_lis):return #这是为了停掉递归程序,你也可以用其他方法
new_dic ={} #里面数据填充
new_dic['name'] = str_lis[start_index]
new_dic['child']=[]
start_index += 1
lis.append(new_dic)
func(new_dic['child'], start_index) #他下一次执行列表是他创建dict里面child里的列表
func(new_lis,start_index)
print(new_lis)
这样就好了,之前一开始看成字典了然后一直没好好改
集合中的元素 长度也不是固定的吗? 如:"a1:b2:c2:d1:"
嗯,都是不固定的。
数据量多的话直接用map好了 效率更高些
用递归三生三世
list.Select(t=>t.Split(":")).Select(t=>new {
name=t[0],
childre=new List{
new {。。。}
}
})
一行代码的事,要什么递归。
//Modify 不好意思 没注意是字符串,字符串更简单,把第二Select 做字符串格式化一下,再用Aggregate连接一下