Transform the string response in a websocket message into JSON format

When receiving a websocket message, I often encounter a response in the form of a string like this:

odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":3,"marketType":1,"name":"1x2","status":"HandedOver","specifiers":"","Outcomes":[]}]

I am looking to parse this as a JSON array, but I am uncertain about the correct method...

https://gist.github.com/fogofogo/4f984c3c5655b5ee0f1b01840fc01b81

(please note that I also need to remove 'odds.1' from the string)

Here are some methods I have attempted, but they did not yield the expected results:

  1. message.json()
  2. JSON.stringify(message)
  3. JSON.parse(message)

Answer №1

If you're looking for a fast solution, consider the following:

const data = `odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":3,"marketType":1,"name":"1x2","status":"HandedOver","specifiers":"","Outcomes":[]}]`;

const dataArray = data.split("odds.1:")[1];
const parsedData = JSON.parse(dataArray);
console.log(parsedData);

Answer №2

The JSON format of your string is incorrect. It should be enclosed within curly braces {} and the key "odds .1" must be enclosed in double quotes as shown below:

{
    "odds .1": [{
        "id": 1,
        "marketType": 10,
        "name": "Double chance",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    }, {
        "id": 2,
        "marketType": 11,
        "name": "Draw no bet",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    }, {
        "id": 3,
        "marketType": 1,
        "name": "1x2",
        "status": "HandedOver",
        "specifiers": "",
        "Outcomes": []
    }]
}

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

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Giving identification to a pair of elements located within the same column

Struggling with assigning IDs to two elements in a single column - a dropdown and a text element. Managed it in the first scenario, but encountering issues in the second one. Seeking assistance on this matter. Scenario 1: <td> <sele ...

Exploring Kotlin to retrieve information from Json fetch results

I am retrieving JSON data from this URL using OKhttp. My coding language of choice is Kotlin. { "CountryName": [{ "Country": "India", "CountryCode": "+91", "Population": "545121546846" }, { "country ": "Pakistan", ...

Jade fails to show image in route with parameter

Currently, I am utilizing express 4 and have images saved in the uploads directory. This is a snippet of my code: app.use(express.static(__dirname + '/uploads')); //This part works app.route('/') .get(function (req, res) { ...

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Buttons in Laravel are shifting unexpectedly

There are three buttons available with different functions. <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('update') ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

Update and swap out outdated material

Struggling with replacing old content in a div after using AJAX. The issue is that both the new and old content are appearing inside the div. Here is my current Ajax code: $('#vu').on("click", function(e){ $.ajax({ url: 'url to pag ...

What could be causing the data in getServerSideProps to be altered?

After fetching data from an API and passing it to index.js using getServerSideProps, I noticed that the prop array is initially in order by rank [1, 2, 3, etc]. Here's an example of the data: [ {rank: 1, price: 123}, {rank: 2, price: 1958}, {rank: ...

What is the best way to handle JSON parsing and writing in C++?

Can someone provide guidance on reading and writing a JSON file in C++? I am planning to use the file to store player information and settings for a simple number guessing game I'm developing. It's a basic console game, but it will help me learn ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Error Encountered when Attempting to Retry AI SDK on Vercel's

I've been implementing code from the official AI SDK website but unfortunately, the code is not functioning properly. The error message I'm encountering is: RetryError [AI_RetryError]: Failed after 3 attempts. Last error: Failed to process error ...

Offspring maintain a certain position within the larger framework of their parent on a

When resizing the parent wrap container, how can I ensure that the pin (red dot) on the image maintains its relative position? To see the issue, resize the wrap container. #wrap{ position: absolute; width: 100%; height: 100%; top: 0; l ...

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

Tips on retrieving a specified string from within an array of strings

I need help extracting the inner string from this array within a string: '["sgrdalal21"]' Can someone provide guidance on how to accomplish this? ...