嵌套的dicts和lists/glom-lib-python



我正在尝试访问深度嵌套列表和字典。我正在试用glom库,但是当尝试检索"时,我的Third_KV密钥不能在下面的JSON对象上工作;国家;

from glom import glom
target = {
"Result": {
"Topics": [
{
"A": "abc",
"D": 0,
"Questions": [
{
"E": "jklm",
"P": "dsfs",
"Answers": [
{
"first": "string",
"second": "string",
"Country": "CH"
},
{
"first": "string",
"second": "string",
"Country": "NL"
}
]
}
]
}
]
}
}
path = {
"First_KV": ("Result.Topics", ["Questions"]),
"Second_KV": ("Result.Topics", [("Questions", ["Answers"])]),
"Third_KV": ("Result.Topics", [("Questions", "Answers", ["Country"])])
}
countries = glom(target, path["Third_KV"])

不太清楚你想要什么样的json/array/结构,但在不依赖任何库的情况下,你可以不使用简单的map((吗?例如

const jsonTest = {
"Result": {
"Topics": [{
"A": "abc",
"D": 0,
"Questions": [{
"E": "jklm",
"P": "dsfs",
"Answers": [{
"first": "CHfirstCountry",
"second": "CHsecondCountry",
"Country": "CH"
},
{
"first": "NLfirstCountry",
"second": "NLsecondCountry",
"Country": "NL"
}
]
}]
}]
}
};
const AnswersArray = jsonTest.Result.Topics[0].Questions[0].Answers;
let dictPerCountry = new Object();
AnswersArray.map((eachElement) => {
dictPerCountry[eachElement.Country] = [eachElement.first, eachElement.second];
});
console.log({
dictPerCountry
});

dictPerCountry看起来是这样的:

{
"dictPerCountry": {
"CH": [
"CHfirstCountry",
"CHsecondCountry"
],
"NL": [
"NLfirstCountry",
"NLsecondCountry"
]
}
}

答案是"列表";键入也会丢失它的方括号。检查以下模式以获得国家

pattern = ('Result.Topics', [('Questions', [('Answers', ['Country'])])])

所以你需要改变你的字典"路径";成为

path = {
"First_KV": ("Result.Topics", ["Questions"]),
"Second_KV": ("Result.Topics", [("Questions", ["Answers"])]),
"Third_KV": ('Result.Topics', [('Questions', [('Answers', ['Country'])])])
}

最新更新