How can I remove escape sequences from JSON.stringify so that it's human-readable?

前端 未结 4 2072
走了就别回头了
走了就别回头了 2020-12-10 17:10

When I call JSON.stringify() on a complex object in JavaScript, it produces a string with lots of escape sequences (\\\", \\\\\", etc.).

How can I make it create a h

4条回答
  •  有刺的猬
    2020-12-10 17:36

    You can use the replacer. The second parameter provided by JSON.stringify.Replacer could be a function or array.

    In your case we can create a function which replaces all the special characters with a blank space.The below example replaces the whitespaces and underscores.

    function replacer(key, value) {
      return value.replace(/[^\w\s]/gi, '');
    }
    
    var foo = {"a":"1","b":2};
    var jsonString = JSON.stringify(foo, replacer);
    

    If you simply want to replace the one special character, use:

    JSON.stringify({ a: 1, b: 2 }, null, '\t');
    

    For more information on replacer, check the MDN page JSON.stringify().

提交回复
热议问题