skip to Main Content

I have a json file where null means no value. I am trying to read from another field when the first value I am looking for is found to be null. But for the life of me I cannot figure out the syntax to achieve my goal.

>import json
>import urllib.request,urllib.parse,urllib.error        
>f h=urllib.request.urlopen('http://mrdata.usgs.gov/geology/state/json/IAXs;0')
>info=json.load(fh)
>if info['age'][0][min_epoch'] == None:
>    GEO_AGE = info['age'][0]['cmax_age']
>else:
>    GEO_AGE = info['age'][0]['min_epoch']
>print('AGE: ', GEO_AGE)

When this prints the result is:
AGE: Paleoproterozoic

This result is correct but for a reason I cannot explain…
The ‘cmax_age’ string for when the ‘min_epoch’ is null or empty is, indeed, ‘Paleoproterozoic’

However when I substitute the following:
fh = urllib.request.urlopen(‘http://mrdata.usgs.gov/geology/state/json/IACAe;0’

The result is the same
AGE: Paleoproterozoic

When, in fact, the output should be
AGE: Middle-Cambrian

`

2

Answers


  1. When I run the code as you stated I get the expected result:

    import json
    import urllib.request,urllib.parse,urllib.error
    fh=urllib.request.urlopen('http://mrdata.usgs.gov/geology/state/json/IACAe;0')
    info=json.load(fh)
    if info['age'][0]['min_epoch'] == None:
        GEO_AGE = info['age'][0]['cmax_age']
    else:
        GEO_AGE = info['age'][0]['min_epoch']
    print('AGE: ', GEO_AGE)
    

    AGE: Middle-Cambrian

    Login or Signup to reply.
  2. I don’t see any issues with your code and it works. Please refer below:

    import json
    import urllib.request,urllib.parse,urllib.error    
    
    fh=urllib.request.urlopen('http://mrdata.usgs.gov/geology/state/json/IAXs;0')
    info=json.load(fh)
    if info['age'][0]['min_epoch'] == None:
        GEO_AGE = 2 or info['age'][0]['cmax_age']
    else:
        GEO_AGE = 1 or info['age'][0]['min_epoch']
    print('AGE: ', GEO_AGE)
    

    Here is another simplified version using "or":

    import json
    import urllib.request,urllib.parse,urllib.error    
    
    def print_geo_age(url):
        fh=urllib.request.urlopen(url)
        info=json.load(fh)
        GEO_AGE = info['age'][0]['min_epoch'] or info['age'][0]['cmax_age']
        print('AGE: ', GEO_AGE)
    
    if __name__ == "__main__":
        print_geo_age('http://mrdata.usgs.gov/geology/state/json/IAXs;0')
        print_geo_age('http://mrdata.usgs.gov/geology/state/json/IACAe;0')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search