Edon
Edon

Reputation: 1216

Quoting values with JSON.stringify

I have an object I'm creating that looks like this:

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');

However, I need the "p" values in this object to be wrapped in quotation marks. As-is it just prints out the values without quotation marks.

I tried escaping the quote characters, via:

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

Which turns out like this, I also tried doing this:

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

Which outputs this.

How can I get the p values to be wrapped in quotations marks, i.e: "139500000" ?

Upvotes: 2

Views: 739

Answers (3)

user663031
user663031

Reputation:

A string-valued property will be stringified as a string, that is, with quotation marks.

let outputOut = {
    "_id": id[i],
    "regNum": code[i],
    "sd": sd[i],
    "pd": ptOut,
    "p": String(p[i]),
         ^^^^^^^^^^^^
...}

Another idea is to use the replacer parameter to JSON.stringify:

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816394

I need the "p" values in this object to be wrapped in quotation marks.

In other words you, want these values to be strings. Strings in JSON are represented as "...". It seems like p[i] is a number. You can explicitly convert a value to a string by calling String(x) or x.toString():

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

Upvotes: 1

Rafi Ud Daula Refat
Rafi Ud Daula Refat

Reputation: 2257

This works for me.

var value = 1023;

var p = '\"'+ value + '\"';
console.log(p);

You can check the fiddle i have created.

https://jsfiddle.net/Refatrafi/1dkhjpjw/

Upvotes: -1

Related Questions