Zohaib Asif
Zohaib Asif

Reputation: 111

Parsing GeoJson data in golang

I want to parse a JSON file that contains a feature collection of a country's regions.

I am using this package https://github.com/tidwall/geojson

I opened the file like this:

jsonFile, err := os.Open("filename.json")
if err != nil {
    return nil, err
}
defer jsonFile.Close()

data, err := ioutil.ReadAll(jsonFile)
if err != nil {
    return nil, err
}

And then I parse the file using this:

obj, err := geojson.Parse(string(data), geojson.DefaultParseOptions)
if err != nil {
    return nil, err
}

but it returns a single geojson.Object and I want a list of features

Can someone help me with this

Upvotes: 2

Views: 739

Answers (1)

Zohaib Asif
Zohaib Asif

Reputation: 111

Problem solved

// open json file

jsonFile, err := os.Open(filename)
if err != nil {
    return nil, err
}
defer jsonFile.Close()

// read the file

data, err := ioutil.ReadAll(jsonFile)
if err != nil {
    return nil, err
}

// parse into a single geojson.Object

obj, err := geojson.Parse(string(data), geojson.DefaultParseOptions)
if err != nil {
    return nil, err
}

// typecast geojson.Object into geojson.FeatureCollection

fc, ok := obj.(*geojson.FeatureCollection)
if !ok {
    return nil, errors.Newf(errors.Internal, nil, "cannot convert into feature collection")
}

Upvotes: 1

Related Questions