Why does JSON.parse need to be run twice - once for a string and once for an object?

When I send a JSON string via websocket (Socket.io) from a Node.js server to a client's browser, I find that I have to execute the JSON.parse function twice in order to extract an object from the received JSON string. This behavior is confusing to me.

The server is responsible for sending a JSON string to the client:

dataString = '{"test": [ {"M": "A", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "B", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}, {"M": "C", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "D", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}]}'
    let data = JSON.stringify(dataString);  
      socket.emit('test', data );

Upon receiving the string on the client side, it appears as follows:

"{\"test\": [ {\"M\": \"A\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"},{\"M\": \"B\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"}, {\"M\": \"C\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"},{\"M\": \"D\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"}]}\n"

To extract an object, I find that I need to execute the json.parse function twice. The first time, I receive a string:

{"test": [ {"M": "A", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "B", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}, {"M": "C", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "D", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}]}

Here is the code on the client side:

      socket.on('test', function (message) {

      var rec = message;
      var transfer = JSON.parse(rec);
      alert(transfer);
      var transfer = JSON.parse(transfer);
      alert(transfer);

  })

Answer №1

thanks to your conversion of the string provided here

  let data = JSON.stringify(dataString);  

How about parsing your dataString as JSON before sending it to the client?

let data = JSON.parse(dataString);  
  socket.emit('test', data );

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 causing this issue? Error: [$compile:nonassign] The expression 'undefined' cannot be assigned! AngularJS 1.5

I'm currently working on developing a component to post "Tweets" on my personal website. However, I am facing an issue where I cannot input any text into the textarea. Below is an image showcasing the error: Please review my code in the file "editor ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

The component you are trying to import requires the use of useState, which is only compatible with a Client Component. However, none of the parent components have been designated with the "use client" tag

I encountered an issue with the code snippet below in my Next.js app directory when utilizing useState: When trying to import a component that requires useState, I received this error message. It seems that the parent components are marked as Server Co ...

What is the most effective method for extracting data from a JSON response using the requests library?

I'm currently working with the Python requests module to make a RESTful GET request to a server. The response I receive is in JSON format, consisting of a list of lists. Can anyone suggest the most effective method to convert this JSON response into ...

Performing unit testing on two services that reside in separate modules using the Jasmine testing framework

I have developed a service in Angular and you can view it on this PLUNKER. In the RouteService, I am injecting CommonService, $rootRouter, ModalService. Please note the following module structure : CommonService belongs to mysampleapp.core RouteS ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Exploring JSON data and appending it to an array: How to do it?

This is my code snippet for iterating through the JSON "data": [myObject removeAllObjects]; NSDictionary *dic = jsonData[@"data"]; for (NSArray *ar in dic) { [myObject addObject:ar]; } Below is the NSLog output for myObject: myObject: ( ...

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Encountering a parse error when parsing JSON using getJSON

Looking to incorporate some jquery.gantt and it requires data in JSON format. The documentation can be found at () Here is the jQuery code snippet: $(".gantt").gantt({ source: basePath + "system/print_gantt_project_data.php?project_id=" + pro ...

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

Deactivate the other RadioButtons within an Asp.net RadioButtonList when one of them is chosen

Is there a way to disable other asp.net radio buttons when one of them is selected? I have three radio buttons, and I want to disable the other two when one is selected. After doing some research, I managed to disable the other two when the third one is se ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

Using Javascript Reduce to Manipulate Objects

Here is the data I am working with: let info = [ {id: 1, name: "John Doe", type: "A", amount: 100}, {id: 2, name: "Jane Smith", type: "B", amount: 150}, {id: 3, name: "Alice Johnson" ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Submitting a Django form seamlessly without reloading the page

Currently using Django-Angular, I am attempting to submit a form and access the data on the backend. Despite achieving this, I have noticed that the page reloads when saving the form. Is there a way to achieve this without having the page render? forms.py ...