比较 2 JSON 个文件

Compare 2 JSON files

json1 = [
   {
      "id":1,
      "line2":"test",
      "city":"me",
      "country":"GB",
      "postcode":"JJJ LLL"
   },
   {
      "id":2,
      "line2":"test",
      "city":"me",
      "country":"GB",
      "postcode":"AAA BBB"
   },
   {
      "id":3,
      "line2":"test",
      "city":"me",
      "country":"GB",
      "postcode":"LLL RRR"
   },
   {
      "id":4,
      "line2":"test",
      "city":"me",
      "country":"GB",
      "postcode":"AAA BBB"
   },
   {
      "id":5,
      "line2":"test",
      "city":"me",
      "country":"GB",
      "postcode":"CCC DDD"
   }
]

json2 = [
   {
      "unique_id":001,
      "postcode":"JJJLLL"
   },
   {
      "unique_id":002,
      "postcode":"AAABBB"
   },
   {
      "unique_id":003,
      "postcode":"CCCDDD"
   }
]

def main():
    for i in range(len(json1)):
        json1 = json1[i]['postcode']
        json1 = json1.replace(' ', '')

        for i in range(len(json2)):
            json2 = json2[i]['postcode']
            if json1 == json2:
                print('FOUND IT:', json2)
            else:
                print('NONE FOUND')

抱歉,如果示例不准确,我实际上在实际测试中加载了 json 文件。希望这是有道理的,基本上我需要遍历 2 JSON 文件的邮政编码,如果它们匹配 return 则匹配对象。它似乎只循环一次并失败 TypeError: string indices must be integers 或者如果有更好的方法来遍历对象

您正在 for 循环中分配 json 和 json。您应该创建临时变量:

for i in range(len(json1)):
    tmpjson1 = json1[i]['postcode']
    tmpjson1 = tmpjson1.replace(' ', '')

    for i in range(len(json2)):
        tmpjson2 = json2[i]['postcode']
        if tmpjson1 == tmpjson2:
            print('FOUND IT:', tmpjson2)
        else:
            print('NONE FOUND')