Is there some way for ST_AsGeoJSON to return a dictionary instead of a json-string? I want to use this value in another API, which leads to the string being escaped like this instead of being used as a json object (which would make more sense):
{
"id": 1234,
"name": "Somestreet",
"geom": "{\"type\":\"MultiLineString\",\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:3857\"}},\"coordinates\":[[[1738990.19,6133244.29],[1739205.08,6133275.45]]]}"
}
whereas the desired output should be
{
"id": 1234,
"name": "Somestreet",
"geom": {
"type":"MultiLineString",
"crs":{"type":"name","properties":{"name":"EPSG:3857"}},
"coordinates":[[[1738990.19,6133244.29],[1739205.08,6133275.45]]]
}
}
Of course I could deserialize this object first into a dict, and put it in my response, but that seems like a lot of pointless performance waste.
ST_AsGeoJSON
returns plain text, as defined per PGsTEXT
data type. PG has no notion of dictionaries, and if plain text is interpreted as JSON-string or object is primarily a question of serialization (e.g. psycopg2 is happily serializing thoseTEXT
values into valid JSON...albeit probably with quite a bit of regexp effort). However, you can cast the result to PGsJSONB
type and see where that get's you, i.e.ST_AsGeoJSON(<geometry>, <precision>)::JSONB
. – geozelot May 5 '20 at 12:17JSONB
instead ofTEXT
should be a few lines of code, but needs a separate function signature. ...however, I bet on the argument that a cast is even less involved than that. – geozelot May 5 '20 at 12:33