PostgreSQL function's input/output as JavaScript nested objects [closed]
-
07-10-2020 - |
Question
I am looking for a simple/clean way that can be used consistently to automatically input JavaScript nested objects to user-defined PostgreSQL functions and also automatically output to JavaScript nested objects.
Shall I used nested composite types? JSON? other ways? How to parse to/from these types and JavaScript nested objects automatically? Any better thoughts?
Thank you.
Solution
JavaScript nested objects can be easily (and I'd say "naturally") represented using JSON. This is "by definition" of what JSON (JavaScript Object Notation) is.
So, in your use-case use JSON
On the JavaScript side:
- To parse the returned values from PostgreSQL (as strings), use
JSON.parse()
. To convert JSON to a string that can be included in a SQL statement, use
JSON.stringify()
.You can also use some libraries, such as JSON-js, although I've never used it myself.
In PostgreSQL, on top of using json
data type, you might also use jsonb
.
It's got a number of advantages (smaller size, indexability, more functions), and a few differences with json
(order of fields is not preserved, you can't have {"a":1,"a":2}
, and a few other smallish differences that normally don't matter).
See Explanation of JSONB introduced by PostgreSQL. Look also at the second answer.
JSON is not only available in PostgreSQL. Most current databases (MySQL, MS SQL Server, Oracle, SQLite with the JSON1 extension, among others) also support it.