The json.stringify method is inserting additional backslashes into the response sent by res.send()

My API needs to provide the following data in its response.

{ users: 'All users are as follows: [{id: 1}, {id: 2}]'}

The response should be a JSON object with one key value being a JSON array. However, the JSON array is converted into a string because it needs to be concatenated with another string. My current code looks like this:

const array = [{id: 1}, {id:2}]
const string = 'All users are as follows: ' + JSON.stringify(array)
res.send({users: string})

I am using Express for my API. When I view the response in Postman, extra backslashes are added to the string. Strangely, when I use console.log({a: string}) locally, I do not see any of those slashes. The response appears like this:

{users: "[{\"id\":1}, {\"id\":2}]"}

Answer №1

   {users: "[{\"id\":1}, {\"id\":2}]"}

The JSON representation of a response is shown above. In a JSON string, it is enclosed in double quotes ("), and any double quotes within the string should be escaped.

     { "user": " "name" " } , is considered invalid. The correct format is { "user" : "\"name\""}

When displayed in the console, only the escaped character is visible which is why you don't see the actual """ but instead see ".

To learn more about JavaScript grammar, visit:

Using JSON.stringify() converts data into valid JSON strings. Failure to do this would send the data as a JavaScript object rather than proper JSON format.

Sending {name:"test"} will result in [object][object] being displayed as the response.

To achieve the desired output, it's necessary to send the response as text and not as JSON:

const array = [{id: 1}, {id:2}]
const string = 'All users are as follows: ' + JSON.stringify(array)
res.send(`{users: "${string}" }`)

In the res.send function, instead of {users:string}, we use "users:string".

Please note that this approach does not produce valid JSON formatting.

Output:

https://i.sstatic.net/B6UAu.png

Answer №2

Would you mind sharing the code for how you return your response?

Regardless, I handle it like this.

const person = {firstName: "John", lastName: "Doe"};

res.send(person);

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

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Exploring the relationship between dates and daylight savings in Web API OData

In my database table, I have a record for every day of the year with a date and value field. The excerpt below shows the 2015 date range for when daylight savings time (British Summer Time) starts and ends: Source Data: ID Date (dd/mm/yyyy) Value ...

Error occurs after upgrading React app to vite due to node-fetch issue

I'm a bit perplexed by this issue. Transitioning the build tool to vite has been seamless except for encountering this error: No matching export in "node_modules/node-fetch/lib/index.mjs" for import "RequestInit" No matching expor ...

It appears that the JSON format of the HTTP response body returned by Rails is not valid

Currently, in my Rails project, I am utilizing the following method to return a JSON response: def return_json render json: params end Upon inspecting the response using Chrome Developer Tools, everything appears to be correct. However, upon examinin ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Create personalized inclusion route depending on user category

Seeking assistance or advice on implementing dynamic routes in Express at runtime. It may seem confusing, but I'm doing my best to navigate through it. Below is an illustration of the current app routes configuration: app.use('/', r ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

Errors encountered when using Mongoose and TypeScript for operations involving $addToSet, $push, and $pull

I am encountering an issue with a function that subscribes a "userId" to a threadId as shown below: suscribeToThread: async (threadId: IThread["_id"], userId: IUser["_id"]) => { return await threadModel.updateOne( { _id: t ...

ReferenceError: 'document' is not defined in React's server-side rendering

One potential issue is with the library react-modal, but similar problems could arise with other libraries. How should this be handled? server.js import express from 'express'; import React from 'react'; import { match, RoutingCont ...

modify web API response type

I am currently developing a web API project and I need to customize the JSON type being returned. My aim is to return two arrays with a specific format as outlined below: Snippet from my controller public IHttpActionResult GetNOX(){ ------- ...

Do you think it's essential to have a collection of items stored within a specifically named entity?

When it comes to formatting responses in JSON, there are different approaches. Let's consider a simple scenario with a GET /users resource: { "success": true, "message": "User created successfully", "data": [ {"id": 1, "name": "Jo ...

Setting a radio button dynamically based on JSON data by using a select dropdown option

I am looking to generate questions from a pre-selected list using Vue.js. I have successfully implemented this with a radio button that reveals a new set of questions once checked. Now, I want to achieve the same functionality using a dropdown selection. ...

Enhancing passport.authenticate with extra parameter

After already setting fbStrategy.passReqToCallback = true, I came across a tutorial on social authentication services at https://scotch.io/tutorials/easy-node-authentication-linking-all-accounts-together. My goal is to implement this social authentication ...

Ensure users are redirected if there is no cookie present in both express.js and socket.io

Looking for advice on handling unauthorized users in my application I need to redirect the page if no cookie is defined or if the cookie value is null Below is my script with comments on where I think changes are needed. var express = require(' ...

What causes inconsistencies in the functionality of flash errors?

I have been utilizing express-flash for flash messages, which was going smoothly until I implemented a redirection to req.header("Referer"). Specifically, my issue arises when attempting to add a product to a shopping cart, with the condition that it shoul ...

What is the best way to choose checkboxes from data that is passed dynamically?

https://i.stack.imgur.com/L3k59.png I am looking to add an edit feature to my application. When the user clicks on the edit option, they should be taken to a different page with the previously entered value displayed. While I have successfully retrieved ...

Step-by-step guide to initializing data within a service during bootstrap in Angular2 version RC4

In this scenario, I have two services injected and I need to ensure that some data, like a base URL, is passed to the first service so that all subsequent services can access it. Below is my root component: export class AppCmp { constructor (private h ...

Issue with converting valid JSON to XML using XSLT 3.0 json-to-xml() function

The following JSON appears to be valid, but when attempting to transform it using XSLT 3.0's json-to-xml() function, an error related to the JSON syntax is encountered. { "identifier": { "use": "<div xmlns=\"http://www ...

Updating JSON files with jq in a bash script

Struggling with updating a value in a JSON file using the jq command. Can anyone help? Error: [jenkins@devops-dev-02 New]$ jq 'map(if .Tags[11].Key == "Period" then .Tags[11].Value = "Weekly" else . end)' create_snapshot.json ...