JSON:类型错误:字符串索引必须是整数

q9yhzks0  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(111)

我正在尝试过滤以下.json文件示例,其中[“cbaCode”]['HHH']与' 300 '不同:

{
  "took" : 32,
  "timed_out" : false,
  "_shards" : {
    "total" : 12,
    "successful" : 12,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1549,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "ib-prodfulltext-t24-transhist-202211",
        "_type" : "_doc",
        "_id" : "D7JGOQTS2XPVSG6HN",
        "_score" : null,
        "_source" : {
          "accountNbr" : 6900069,
          "accountNbrText" : "6900069",
          "acctApplNbr" : "02",
          "acknowledgementDate" : "2022-11-01T01:46:38.000+01:00",
          "acknowledgementDateText" : "2022-11-01",
          "avoType" : "ADI",
          "bankCode" : "0100",
          "bankingCore" : "T24",
          "bazenType" : "ADI",
          "businessDate" : "2022-11-01",
          "cbaCode" : "10000101002",
          "cbaCodeParts" : {
            "BBB" : "002",
            "HHH" : "100",
            "TT" : "01",
            "VVV" : "001"
          },
          "chargeType" : "SHAR",
          "creditDebitIndicator" : "D",
          "currencyCode" : "CZK",
          ...

我试过:

import json

with open('2022-10.json', 'r') as f:
    input_dict = json.load(f)
output_dict = [x for x in input_dict if not x['HHH'] == "300"]
output_json = json.dumps(output_dict)
print(output_json)

......由此产生:
TypeError:字符串索引必须为整数
我想我错过了查询第5级的json文件,但有点迷失在结构中。
我们会很感激的。

4ioopgfo

4ioopgfo1#

您必须提供Json树中的确切路径:

import json

with open('2022-10.json', 'r') as f:
    input_dict = json.load(f)

output_dict = [x for x in input_dict["hits"]["hits"]
  if not x["_source"]["cbaCodeParts"]["HHH"] == "300"
]

output_json = json.dumps(output_dict)
print(output_json)

只访问顶级数据,也就是字典,只会得到字典的列表,而不是你想要的数组,上面的代码假设你想要循环遍历第二个hits-字段提供的数组。
另外,提供更多的Json文件可能会帮助人们更好地理解您的问题。

相关问题