简体   繁体   English

将Postgres JSONB数组转换为JSON元素的Javascript数组

[英]Convert Postgres JSONB array into Javascript array of JSON elements

I'm having some issues with postgresql(9.4) and javascript. 我在使用postgresql(9.4)和javascript时遇到了一些问题。 I'm trying to convert a jsonb[] datatype into an array/list of json values in javascript. 我正在尝试将jsonb []数据类型转换为javascript中json值的数组/列表。 For simplicity, my example contains only one element(json) in the array. 为简单起见,我的示例在数组中仅包含一个element(json)。

var s = { "player": "{\"{\\\\\"username\\\\\": \\\\\"JetJet13\\\\\", \\\\\"points\\\\\": 525, \\\\\"level\\\\\": 3"}\"}" };

Here's what I have tried so far. 到目前为止,这是我尝试过的。

JSON.parse(s.player); //this gives an error: SyntaxError: Unexpected token }

Here's what I'm looking for. 这就是我要的东西。

var s = { "player": [ {"username": "JetJet13", "points": 525, "level": 3} ] };

Any help will be appreciated. 任何帮助将不胜感激。

Alright, I managed to figure out how to get my desired result. 好吧,我设法弄清楚如何得到我想要的结果。

I've created a function to make things easier. 我创建了一个使事情变得更容易的函数。 Notice that the syntax highlighter gets confused with my regex expressions. 请注意,语法荧光笔与我的正则表达式表达式混淆了。 A correction/alternative regex expression would be appreciated. 校正/替代正则表达式将不胜感激。 I use Sublime Text 3 and it too is not interpreting the regex properly. 我使用Sublime Text 3,它也不能正确解释正则表达式。

var convertJSONarray = function(s){

  var step1 = s.replace(/"{/g,'{').replace(/}"/g,'}').replace(/\\/g,"");
  //step1 = "{ {}, {}, {},...}"
  var step2 = "[" + step1.slice(1,-1) + "]";
  // step2 = "[ {}, {}, {}, ...]"
  var step3 = JSON.parse(step2);
  // step3 = [ {}, {}, {}, ...] the desired result :)
  return step3;
 };

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM