Transform JSONB arrays from Postgres into a JavaScript array containing individual JSON elements

Having some challenges with postgresql(9.4) and javascript. I'm attempting to convert a jsonb[] datatype into an array/list of JSON values in javascript, containing only one element(json) for simplicity.

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

This is what has been attempted so far:

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

This is the desired result:

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

Any assistance on this matter would be greatly appreciated.

Answer №1

After some trial and error, I finally cracked the code to achieve my intended outcome.

To streamline the process, I developed a custom function. It seems like the syntax highlighter is getting confused with my regex expressions. Any suggestions for correcting or providing an alternative regex expression would be greatly appreciated. Even Sublime Text 3 is having trouble interpreting the regex correctly.

var convertToJSON = function(input){

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

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

The on-screen keyboard using JQuery and CSS is not working properly on an HTML redesign

UPDATE - Check out the modified version here: https://codepen.io/anon/pen/wZQjQy Here is the original for reference: https://codepen.io/anon/pen/YMRLBN (had to utilize CodePen, as simply adding a snippet here doesn't link the CSS) I essentially copie ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

No input values were passed to express-validator

In my node app, I am using express-validator and encountering validation errors for all 4 form fields ("A name is required" and so on). Strangely, when I console.log the errors variable, all values are blank: errors: [{value: '', msg: 'A na ...

Executing another component's method from the render method: a step-by-step guide

I keep encountering the error message highlighted below: TypeError: _AuthenticationService__WEBPACK_IMPORTED_MODULE_2__.default.checkUserLoggedIn is not a function This error occurs when I try to execute this specific call. import AuthenticationService fr ...

When beginning a new React project, I encounter this issue

Every time I try to run npm start, an error pops up. How can I fix this issue? ...

The C programming language does not correctly output the iterative function, which should return a number that is not included in the sum of user-entered data or the data array

Currently tackling an assignment where I need to create a program that identifies the smallest positive integer not present in an array, and cannot be formed by adding two numbers within the array. Two functions need to be utilized for this task: int ...

What is the reason behind Chrome's fullscreen mode turning the background black?

I created a webpage with full-screen functionality and made sure to use the correct CSS properties to ensure that my gradient background covers the entire screen perfectly. However, I encountered an issue when clicking the full-screen button in Chrome - th ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

What is the best method for ensuring that my JavaScript tracking script has been properly installed on the customer's website?

We provide a SAAS analytics application that functions similarly to Hotjar and Google Analytics. To track user data, our customers must integrate our JavaScript code into their websites. How can we confirm if the script has been successfully integrated in ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

Get the last digit of an integer and change it to a corresponding character in C Programming

I am currently developing a program that involves taking a seed number and generating a sequence of random numbers to create a lottery number based on the last digits. For example, in one scenario, we use the last digits of four numbers (3 4 3 1), while in ...

An issue has occurred in the node-telegram-bot-api module: Unable to locate 'fs', 'net', 'tls' in node-telegram-bot-api

<pre> import React, { Component } from "react"; import { render } from "react-dom"; import Home from "./components/Home.jsx"; const TelegramBot = require('node-telegram-bot-api'); const token = "MY_TOKEN"; const bot = new TelegramBot(token ...

Perform mathematical calculations based on the parameters in the URL using Python

My primary objective is simple: The URL is structured like this: /add?a=1&b=2 I want my function to extract the values of these parameters and perform addition. However, I am currently facing difficulty in achieving this. Below is the code for my add ...

Issue with Datepicker not updating when triggered by event handler

Having an issue with my material-UI datepicker where the date is not updating correctly when I try to select a new one. The initial value set in useState works fine, but I want the datepicker to smoothly update when I choose a different date. You can see a ...

How to convert an object to Json format in Java

We need to convert the Object class into a JSON string. public static String genJson(Response r, Auth auth) { Auth p = new Auth(); ObjectMapper mapper = new ObjectMapper(); String transactionResult = r.getTransactionResult(); ...

Vue.js - The @oninput.native listener does not trigger in b-form-textarea components

I have a Vue application and I am trying to incorporate Facebook inspired buttons inline in a comment form. Previously, I had a plain JavaScript prototype that was functional. However, when integrating it into my Vue app, I encountered issues due to multip ...

Error encountered using Meteor 1.3 autoform/quickform integration

Having recently transitioned to using Meteor 1.3, I've encountered a few challenges related to debugging due to missing imports or exports in tutorials. This particular issue seems to be in the same vein. I wanted to incorporate the autoform package ...