[英]Nested dicts and lists / glom lib python
path = {
"First_KV": ("Result.Topics", ["Questions"]),
"Second_KV": ("Result.Topics", [("Questions", ["Answers"])]),
"Third_KV": ("Result.Topics", [("Questions", "Answers", ["Country"])])
}
actual = glom.glom(read_content, path["Third_KV"])
print(actual)
I am trying to get a more clean way to re-use in order to access deep-nested lists and dictionaries.我试图获得一种更干净的方式来重用,以便访问深度嵌套的列表和字典。 I am experimenting with the glom library however my Third_KV key is unsuccesful- I have tried adapting it quiet a bit.我正在尝试使用glom 库,但是我的Third_KV 密钥不成功-我尝试过让它安静一点。
The data coming from a JSON are several nested dicts and lists.来自 JSON 的数据是几个嵌套的字典和列表。 How to access this third degree dicts in lists, eg with key "Country"?如何访问列表中的这个三级字典,例如使用键“国家”?
{
"Result": {
"Topics": [
{
"A": "abc",
"D": 0,
"Questions": [
{
"E": "jklm",
"P": "dsfs",
"Answers": [
{
"first": "string",
"second": "string",
"Country": "CH"
},
{
"first": "string",
"second": "string",
"Country": "NL"
}
Not very clear what final json/array/structure you want, but without relying on any library, can you not use simple map() eg不是很清楚你想要什么最终的 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 will look like so: dictPerCountry 看起来像这样:
{
"dictPerCountry": {
"CH": [
"CHfirstCountry",
"CHsecondCountry"
],
"NL": [
"NLfirstCountry",
"NLsecondCountry"
]
}
}
Answers are of "list" type too and you are missing its square brackets.答案也是“列表”类型,您缺少方括号。 check below pattern to get the country检查下面的模式以获取国家
pattern = ('Result.Topics', [('Questions', [('Answers', ['Country'])])])
So you need to change your dictionary "path" to be因此,您需要将字典“路径”更改为
path = {
"First_KV": ("Result.Topics", ["Questions"]),
"Second_KV": ("Result.Topics", [("Questions", ["Answers"])]),
"Third_KV": ('Result.Topics', [('Questions', [('Answers', ['Country'])])])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.