我正在尝试清除我从API请求的JSON,因为数据库插入了键名,键值结构并使所有内容混乱,但是不幸的是我无法使用背面,所以我必须清除JSON在前面,问题之一是数据不一定总是相同的结构,因此,我需要一个递归解决方案来迭代所有嵌套的JSON,真正的JSON具有更多的嵌套子对象,但是出于演示目的,我仅展示JSON的一部分。
这是结构的一个示例,但有时结构不相同,有时我没有得到总体或总体值之一。
def reverse(l):
t=""
for i in range(len(l)):
if(l[i]=='A'):
t=t+'T'
elif(l[i]=='T'):
t=t+'A'
elif(l[i]=='C'):
t=t+'G'
elif(l[i]=='G'):
t=t+'C'
return t
def rev(d):
return d[len(d)::-1]
k=input()
p=input()
for i in range(len(p)):
for j in range(4,14):
if (p[i:i+j]==rev(reverse(p[i:i+j]))and i+j<=len(p)):
print(i+1, end=" ")
print(j)
我正在尝试清除所有键名,键值,以获得类似这样的内容:
[
{ "Name": "code", "Value": "18187" },
{ "Name": "date", "Value": "2020-05-10" },
{
"Name": "countries",
"Value": [
[
{ "Name": "id", "Value": "1" },
{ "Name": "name", "Value": "Canada" },
{
"Name": "population",
"Value": [
[
{ "Name": "id", "Value": "1" },
{ "Name": "male", "Value": "1000" }
],
[
{ "Name": "id", "Value": "2" },
{ "Name": "female", "Value": "1000" }
]
]
}
],
[
{ "Name": "id", "Value": "2" },
{ "Name": "name", "Value": "Italy" },
{
"Name": "population",
"Value": [
[
{ "Name": "id", "Value": "1" },
{ "Name": "male", "Value": "1000" }
],
[
{ "Name": "id", "Value": "2" },
{ "Name": "female", "Value": "1000" }
]
]
}
]
]
}
]
答案 0 :(得分:1)
您可以使用使用map
方法的递归函数。
const data = [{"Name":"code","Value":"18187"},{"Name":"date","Value":"2020-05-10"},{"Name":"countries","Value":[[{"Name":"id","Value":"1"},{"Name":"name","Value":"Canada"},{"Name":"population","Value":[[{"Name":"id","Value":"1"},{"Name":"male","Value":"1000"}],[{"Name":"id","Value":"2"},{"Name":"female","Value":"1000"}]]}],[{"Name":"id","Value":"2"},{"Name":"name","Value":"Italy"},{"Name":"population","Value":[[{"Name":"id","Value":"1"},{"Name":"male","Value":"1000"}],[{"Name":"id","Value":"2"},{"Name":"female","Value":"1000"}]]}]]}]
function modify(data) {
return data.map(e => {
if (Array.isArray(e)) return modify(e)
else {
const { Name, Value } = e;
return ({
[Name]: Array.isArray(Value) ?
modify(Value) : Value
})
}
})
}
const result = modify(data);
console.log(result)