Search code examples
javascriptjsonstringify

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" ?


Solution

  • 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]),