Monday, 20 June 2016

Read And Write in JSON file-Python

Here, i am going to demonstrate real life problem.
before some days, one of my friend was gone for an interview in one of the reputed company.
In interview he has given a following problem.

PROBLEM :
Write a program in python which reads a json file containing list of URLs.
Check if any url is non functional.
Save that data to another json file called : output.json

File : input.json
 
{
"url": ["http://www.programminggit.blogspot.in",
          "http://media.caranddriver.com/images/media/638444/porsche-cayman-photo-640546-s-original.jpg",
          "http://static2.consumerreportscdn.org/content/dam/cro/cars/sports/buying_lg_sports_cars.jpg",
          "http://pop.h-cdn.co/assets/cm/15/05/54cb1d27a519c_-_analog-sports-cars-01-1013-de.jpg",
          "http://pop.h-cdn.co/assets/cm/15/05/54cb1d27a519c_-_analog-sports-cars-01-10"]
}


SOLUTION :

import json

data = {}
# read a json file
with open('input.json') as f:
    json_data = json.load(f)
    for key, value in json_data.iteritems():
        data.update({key: []})
        for each_item in value:
        if str(each_item).find('pop') < 0:
            data.get(key).append(each_item)
# write in json file
with open('output.json', 'w') as f:
    json.dump(data, f)


OUTPUT : output.json

{
"url":  ["http://www.programminggit.blogspot.in",
             "http://media.caranddriver.com/images/media/638444/porsche-cayman-photo-640546-s-original.jpg",
              "http://static2.consumerreportscdn.org/content/dam/cro/cars/sports/buying_lg_sports_cars.jpg"]
}

No comments:

Post a Comment