简体   繁体   English

比较 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')

Sorry if the example isn't accurate, I'm actually loading a json file in my actual test.抱歉,如果示例不准确,我实际上在实际测试中加载了一个 json 文件。 Hope this makes sense, basically I need to loop through 2 JSON file's postcode and if they match return the matching object. It seems to only loop once and fails with TypeError: string indices must be integers Or if there's a better way to iterate over the objects希望这是有道理的,基本上我需要遍历 2 个 JSON 文件的邮政编码,如果它们匹配则返回匹配的 object。它似乎只循环一次并失败并显示TypeError: string indices must be integers或者如果有更好的方法来迭代对象

You are reassigning json1 and json2 in your for loop.您正在 for 循环中重新分配 json1 和 json2 。 You should create temporary variables:您应该创建临时变量:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM