我有一些棘手的数据需要处理。基本上我想把结构放到扁平列表中。
用简单的英语,它应该:
"level":1
标记是数组的关键"level":2
或更高标签应嵌套在数组"level":1
,请将其添加到通用NoLevel1
列表tags
仅将if
组合在一起"level":1
具有相同的[{
"title": "Set 1",
"tag": [{
"name": "Animals",
"level": 1
},
{ "name": "Cat",
"level": 2
},
{ "name": "Dog",
"level": 3
}
]
},
{
"title": "Set 2",
"tag": [{
"name": "Fruits",
"level": 1
},
{ "name": "Apple",
"level": 2
}]
},
{
"title": "Set 3",
"tag": [{
"name": "Fruits",
"level": 1
},
{ "name": "Orange",
"level": 3
}]
},
{
"title": "Set 4",
"tag": [{
"name": "Cars",
"level": 2
}]
},
{
"title": "Set 5",
"tag": [{
"name": "Random!",
"level": 3
}]
}]
值我的数据如下:
[{
"name": "Animals",
"level":1,
"tag_child": [{
"name": "Cat",
"level": 2
},
{ "name": "Dog",
"level": 3
}]
},
{
"name": "Fruits",
"level":1,
"tag_child": [{
"name": "Apple",
"level": 2
},
{ "name": "Orange",
"level": 3
}]
},
{
"name": "NoLevel1",
"level":1,
"tag_child": [{
"name": "Cars",
"level": 2
},
{ "name": "Random!",
"level": 3
}]
}]
我想要的输出是:
import json
with open("Test.json") as json_file:
l = json_data = json.load(json_file)
for i in thedata:
if i['tag']['level'] > 1:
我已经加载了数据,但在为数据提供结构方面还没有进一步说明。
$valueToWrite = mb_convert_encoding($value, 'Windows-1252');
答案 0 :(得分:1)
我没有对此进行测试,但这样的事情应该有效。如果这不是您想要的,请进行自己的更改。但是这肯定会让你开始。
import json
with open("Test.json") as json_file:
json_data = json.load(json_file)
generic = []
result = []
for i in json_data:
if any(d['level'] == 1 for d in i['tag']):
tag_data = {}
tag_child = []
for tag in i['tag']:
if tag['level'] == 1:
tag_data['name'] = tag['name']
tag_data['level'] = 1
else:
tag_child.append(tag)
filtered = {tuple((k, d[k]) for k in sorted(d) if k in ['name']): d for d in tag_child}
tag_data['tag_child'] = list(filtered.values())
if any(d['name'] == tag_data['name'] for d in result):
for t in result:
if t['name'] == tag_data['name']:
t['tag_child'] = t['tag_child'] + tag_child
filtered = {tuple((k, d[k]) for k in sorted(d) if k in ['name']): d for d in t['tag_child']}
t['tag_child'] = list(filtered.values())
else:
result.append(tag_data)
else:
for tag in i['tag']:
generic.append(tag)
tag_data = {}
tag_data['name'] = 'NoLevel1'
tag_data['level'] = 1
tag_data['tag_child'] = generic
result.append(tag_data)
print(json.dumps(result))