Home > database >  Compare 2 JSON files
Compare 2 JSON files

Time:04-07

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. 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

CodePudding user response:

You are reassigning json1 and json2 in your for loop. 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')
  • Related