3

I'm trying to build a GeoJSON file with Python geojson module consisting on a regular 2-d grid of points whose 'properties' are associated to geophysical variables (velocity,temperature, etc). The information comes from a netcdf file.

So the code is something like that:

from netCDF4 import Dataset
import numpy as np
import geojson

ncfile = Dataset('20140925-0332-n19.nc', 'r')
u = ncfile.variables['Ug'][:,:] # [T,Z,Y,X]
v = ncfile.variables['Vg'][:,:]
lat = ncfile.variables['lat'][:]
lon = ncfile.variables['lon'][:]

features=[]
for i in range(0,len(lat)):
     for j in range(0,len(lon)):
         coords = (lon[j],lat[i])
         features.append(geojson.Feature(geometry = geojson.Point(coords),properties={"u":u[i,j],"v":v[i,j]})) 

In this case the point has velocity components in the 'properties' object. The error I receive is on the features.append() line with the following message:

*ValueError: -5.4989638 is not JSON compliant number*

which corresponds to a longitude value. Can someone explains me whatcan be wrong ?

user1259970
  • 333
  • 3
  • 14
  • The only code in the geojson module which corresponds to your error is found here: https://github.com/frewsxcv/python-geojson/blob/bfea4a814632806761093eafcd50de27ec013de7/geojson/geometry.py#L35-L40 Can you try a `class(velocity).__name__` to see what the class of your velocity number is? – bretmattingly Jun 13 '16 at 18:57
  • All are numpy arrays of class "numpy.float32". – user1259970 Jun 14 '16 at 08:10

2 Answers2

2

I have used simply conversion to float and it eliminated that error without need of numpy.

coords = (float(lon[j]),float(lat[i]))
vhaska
  • 66
  • 7
1

I found the solution. The geojson module only supports standard Python data classes, while numpy extends up to 24 types. Unfortunately netCDF4 module needs numpy to load arrays from netCDF files. I solved using numpy.asscalar() method as explained here. So in the code above for example:

  coords = (lon[j],lat[i])

is replaced by

  coords = (np.asscalar(lon[j]),np.asscalar(lat[i]))

and works also for the rest of variables coming from the netCDF file. Anyway, thanks Bret for your comment that provide me the clue to solve it.

Community
  • 1
  • 1
user1259970
  • 333
  • 3
  • 14