Python: How to add content of file to list from position
Question: I have a JSON file containing various objects each containing elements. With
my python script, I only keep the objects I want, and then put the elements I
want in a list. But the element has a prefix, which I'd like to suppress form
the list. The post-script JSON looks like that:

    
    
    {
    
          "ip_prefix": "184.72.128.0/17",
    
          "region": "us-east-1",
    
          "service": "EC2"
    }
    

The "IP/mask" is what I'd like to keep. The List looks like that:

'"ip_prefix": **"23.20.0.0/14"** ,'

So what can I do to only keep **"23.20.0.0/14"** in the list?

Here is the code:

    
    
    json_data = open(jsonsourcefile)
    data = json.load(json_data)
    print (destfile)
    d=[]
    
    for objects in (data['prefixes']):
        if servicerequired in json.dumps(objects):
            #print(json.dumps(objects, sort_keys=True, indent=4))
            with open(destfile, 'a') as file:
                file.write(json.dumps(objects, sort_keys=True, indent=4 ))
    with open(destfile, 'r') as reads:
        liste = list()
        for strip in reads:
            if "ip_prefix" in strip:
                strip = strip.strip()
                liste.append(strip)
    
        print(liste)
    

Thanks, dersoi


Answer: I've refactored your code, try this out:

    
    
    import json 
    
    with open('sample.json', 'r') as data:
        json_data = json.loads(data.read())
        print json_data.get('ip_prefix')
    
    # Output: "184.72.128.0/17"
    

