4

我正在尝试访问深层嵌套列表和字典。我正在尝试使用 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"])

4

2 回答 2

2

不是很清楚你想要什么最终的 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"
    ]
  }
}
于 2021-10-28T05:03:33.967 回答
1

答案也是“列表”类型,您缺少方括号。检查下面的模式以获取国家

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'])])])
}
于 2021-10-28T05:08:10.177 回答