Encapsulating data with JSON.stringify

I'm currently working on creating an object that has the following structure:

let outputOut = {
    "_id": id[i],
    "regNum": code[i],
    "sd": sd[i],
    "pd": ptOut,
    "p": p[i],
...}
//output 
fs.writeFile('./output/file.json', JSON.stringify(output, null, 2), 'utf-8');

The issue I'm facing is that I need the values of "p" within this object to be enclosed in quotation marks. Currently, the values are being printed out without any quotes.

I attempted to escape the quote characters by using the following format:

"p": "\"" + p[i] + "\"'",

This resulted in this. I also tried this approach:

"p": '"' + p[i] + '"',

However, it produced this.

Does anyone know how I can ensure that the values of variable p are wrapped in quotation marks, like so: "139500000"?

Answer №1

I'm looking to enclose the "p" values within this object in quotation marks.

Essentially, you want these values to be converted into strings. In JSON, strings are denoted by "...". It appears that p[i] is currently a numeric value. To change it into a string, you can use either String(x) or x.toString():

"p": String(p[i]),

Answer №2

When dealing with a string-valued property, it will be converted into a string format with quotation marks around it.

let result = {
    "_id": identification[i],
    "registrationNumber": code[i],
    "startingDate": start[i],
    "completionDate": endOut,
    "percentage": String(percent[i]),
         ^^^^^^^^^^^^
...}

Alternatively, consider utilizing the replacer parameter in the JSON.stringify function:

JSON.stringify(result, function(key, value) {
  if (key === 'percentage') value = String(value);
  return value;
});

Answer №3

Successfully tested and working for me.

const num = 2048;

const result = '\"'+ num + '\"';
console.log(result);

Feel free to view the demo on my personal fiddle link!

https://jsfiddle.net/UniqueUser/abcd1234/

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

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

Can you provide guidance on accessing the response API from Twitter?

Currently, I am in the process of creating a toy project using React and Express.js, similar to a basic SNS website. Usually, the server responds to a client request by sending back JSON data containing all the necessary information for rendering articles ...

Revamp HTML <font size=1-7> with the use of CSS or JavaScript

I've been developing a prototype application that incorporates a plugin utilizing the deprecated HTML feature. Can I set custom pixel sizes for each font size ranging from 1 to 7? Currently, I'm contemplating using CSS zoom/scale properties, bu ...

The submit button fails to produce any result

I have a submit button in a contact form that triggers PHP code to send an email. However, when I press the button nothing happens - not even the PHP code is displayed as it should be if PHP were not installed. Interestingly, I have tested other simple mai ...

node.js: The Yahoo weather jQuery plugin fails to display any data

After successfully implementing node.js with jQuery and the plugin from , I now aim to utilize the weather data for a different purpose rather than directly inserting it into the HTML. However, I am encountering difficulties in accessing or displaying the ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Obtain a set of items from a JSON result and transfer them to the database

I have a table that displays object data triggered by a dropdownbox .change function. However, I also need to submit this data to a database. While I can display the data when the dropdown changes, I'm struggling with retrieving the list of objects an ...

Here is how you can pass two callback functions to React.cloneElement:

Recently, I encountered an issue where one of the callbacks passed to a child component using React.cloneElement was always present while the other was undefined. Specifically, activeRow was consistently available but deactivateRow remained undefined. I ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

What steps should I take to resolve issues with the npm installation on Linux?

I'm encountering an issue while attempting to use npm install in order to install a package. Despite my attempts to update and re-download from the root directory, I am unable to resolve the error. hackathonday1-2 git:(save-button) ✗ npm install f ...

Issues with zoom functionality not functioning properly within IE11

I am currently developing an application with Angular that is designed to be compatible with tablets and touch-enabled devices. One of the key features I want to implement is the ability for users to zoom/scale up the app, especially for those with visual ...

Alter the Cascading Style Sheets (CSS) value by accessing a

I have two files, keyboard.css and keyboard.js. My objective is to modify a CSS rule: .ui-keyboard div { font-size: 1.1em; } Is there an alternative method to change the font size without utilizing $(".ui-keyboard div").css()? I want the modification ...

"Integrate a URL segment into the primary URL with the help of AngularJS or JavaScript

One interesting case involves a URL path that is structured in the following way. http://localhost:12534/urlpart1/urlpart2?querystring=140 The challenge here is to replace "urlpart2" with "urlpart3" using either javascript or AngularJS. One approach is t ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

Choose the minimum price from the JSON response of the API

I have made an AJAX request to an API and received the following JSON response below. I am trying to extract the lowest 'MinPrice' from the 'Quotes' data but finding it challenging to determine the best approach. One method I am consid ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...