diff --git a/osm.go b/osm.go index 76c3532..ada25c2 100644 --- a/osm.go +++ b/osm.go @@ -3,7 +3,6 @@ package osm import ( "encoding/xml" "fmt" - "regexp" ) // These values should be returned if the osm data is actual @@ -367,13 +366,21 @@ func (o *OSM) UnmarshalJSON(data []byte) error { return nil } -var jsonTypeRegexp = regexp.MustCompile(`"type"\s*:\s*"([^"]*)"`) +type typeStruct struct { + Type string `json:"type"` +} func findType(index int, data []byte) (string, error) { - matches := jsonTypeRegexp.FindAllSubmatch(data, 1) - if len(matches) > 0 { - return string(matches[0][1]), nil + ts := typeStruct{} + err := unmarshalJSON(data, &ts) + if err != nil { + // should not happened due to previous decoding succeeded + return "", err + } + + if ts.Type == "" { + return "", fmt.Errorf("could not find type in element index %d", index) } - return "", fmt.Errorf("could not find type in element index %d", index) + return ts.Type, nil } diff --git a/osm_test.go b/osm_test.go index f615e23..a80c807 100644 --- a/osm_test.go +++ b/osm_test.go @@ -183,7 +183,10 @@ func TestOSM_UnmarshalJSON(t *testing.T) { {"type":"way","id":456,"visible":false,"timestamp":"0001-01-01T00:00:00Z","nodes":[]}, {"type":"relation","id":789,"visible":false,"timestamp":"0001-01-01T00:00:00Z","members":[]}, {"type":"changeset","id":10,"created_at":"0001-01-01T00:00:00Z","closed_at":"0001-01-01T00:00:00Z","open":false}, - {"type":"user","id":16,"name":"","img":{"href":""},"changesets":{"count":0},"traces":{"count":0},"home":{"lat":0,"lon":0,"zoom":0},"languages":null,"blocks":{"received":{"count":0,"active":0}},"messages":{"received":{"count":0,"unread":0},"sent":{"count":0}},"created_at":"0001-01-01T00:00:00Z"}, + {"type":"user","id":16,"name":"","img":{"href":""}, + "changesets":{"count":0},"traces":{"count":0},"home":{"lat":0,"lon":0,"zoom":0},"languages":null, + "blocks":{"received":{"count":0,"active":0}},"messages":{"received":{"count":0,"unread":0},"sent":{"count":0}}, + "created_at":"0001-01-01T00:00:00Z"}, {"type":"note","id":15,"lat":0,"lon":0,"date_created":null,"date_closed":null,"comments":null} ]}`) @@ -244,6 +247,25 @@ func TestOSM_UnmarshalJSON_Version(t *testing.T) { } } +func TestOSM_UnmarshalJSON_Type(t *testing.T) { + data := []byte(`{ + "version":0.6,"generator":"osm-go", + "elements":[ + {"type":"relation","id":120,"timestamp":"0001-01-01T00:00:00Z","tags":{"type":"route"}}, + {"tags":{"type":"route","other":"asdf"},"type":"relation","id":121,"timestamp":"0001-01-01T00:00:00Z"} + ]}`) + + o := &OSM{} + err := json.Unmarshal(data, &o) + if err != nil { + t.Fatalf("unmarshal error: %v", err) + } + + if l := len(o.Relations); l != 2 { + t.Errorf("incorrect number of relations: %v", l) + } +} + func TestOSM_MarshalXML(t *testing.T) { o := &OSM{ Version: "0.7",