Home > Net >  JSON.stringify() escapes line ending character for values
JSON.stringify() escapes line ending character for values

Time:01-03

For example I have following code:

var obj = {
    name: "alex",
    lastname: "aaa",
    portfolio: {
        stocks: "TSLA, BA"
    },
    comments: "some\nrandom\ndescription"
};

console.log("JSON OUT:\n"   obj.comments);

console.log("STRING OUT:\n"   JSON.stringify(obj, null, 2));

Which results in:

JSON OUT:
some
random
description
STRING OUT:
{
  "name": "alex",
  "lastname": "aaa",
  "portfolio": {
    "stocks": "TSLA, BA"
  },
  "comments": "some\nrandom\ndescription"
}

As you can see it escapes '\n' characters in comments value. In other words, it replaces '\n' with '\\n' in resulting string. Is there any possibility how I could avoid this behavior? I tried using replace function in stringify() 2nd parameter which does something like that return v.replace(/\\n/g, "\n"); but it newer worked (probably because original string contains just \n and final string gets screwed up after replace function finishes).

There is also another solution with involves .replace(/\\n/g, "\n") on final string, but it screw up all blank spaces which stringify() function adds:

{
  "name": "alex",
  "lastname": "aaa",
  "portfolio": {
    "stocks": "TSLA, BA"
  },
  "comments": "some
random
description"
}

But I want well-formatted human-readable string in output after JSON.stringify() call and I don't need to convert it back to JSON later:

{
  "name": "alex",
  "lastname": "aaa",
  "portfolio": {
    "stocks": "TSLA, BA"
  },
  "comments": "some
  random
  description"
}

CodePudding user response:

You could improve your replace-logic, and capture the original indent. Then reinsert that indent when replacing the individual \n:

var obj = {
    name: "alex",
    lastname: "aaa",
    portfolio: {
        stocks: "TSLA, BA"
    },
    comments: "some\nrandom\ndescription"
};

let result = JSON.stringify(obj, null, 2).replace(/^(\s*)(.*\\n.*)$/gm, (line, indent) =>
    line.replace(/\\n/g, "\n"   indent)
);
console.log(result);

  • Related