如何以字符串形式转换PostgreSQL数组"{1,2,3,4}"
到javascript / typescript数组:[1,2,3,4]
。
数组中的值必须是数字类型。
我尝试了 replace 和 split 的解决方案,但是它返回字符串值。
var test = "{1,2,3,4}";
test = test.replace("{", "");
test = test.replace("}", "");
//test = test.replace(/\{|\}/gm, "") //regex replace
test.split(",") //['1', '2', '3', '4']
答案 0 :(得分:1)
一个更干净的解决方案,不涉及仅用于解析JSON字符串:
test = test.match(/[\w.-]+/g).map(Number)
但是在处理数据库时,通常不应该自己解析数据,除非您正在编写驱动程序(但是对于Postgresql已经有不错的选择了)。
答案 1 :(得分:0)
我找到了使用JSON.parse的解决方案,但这在转换之前也需要 replace 。
var test = "{1,2,3,4}";
test = test.replace("{", "[");
test = test.replace("}", "]");
JSON.parse(test) //[1, 2, 3, 4]
测试是否为数组大小建立一个字符串:100000〜900000:https://stackblitz.com/edit/typescript-gavnpg
答案 2 :(得分:0)
JSON.parse("[" + test.slice(1, test.length-1) + "]")