{"id":257,"date":"2018-04-30T17:42:05","date_gmt":"2018-04-30T17:42:05","guid":{"rendered":"https:\/\/restfulapi.net\/?p=257"},"modified":"2021-09-27T23:05:37","modified_gmt":"2021-09-27T17:35:37","slug":"json-stringify","status":"publish","type":"post","link":"https:\/\/restfulapi.net\/json-stringify\/","title":{"rendered":"JSON stringify()"},"content":{"rendered":"\n

The JSON.stringify()<\/strong> function, as name suggests, converts a JavaScript value to a serialized JSON string.<\/p><\/blockquote>\n\n\n\n

JSON.stringify()<\/code> can optionally use a replacer function<\/strong> to replace values using custom logic.<\/p>\n\n\n\n

1. Syntax<\/h2>\n\n\n\n

The syntax of the JSON.stringify()<\/code> method is:<\/p>\n\n\n\n

JSON.stringify(value[, replacer[, space]])<\/code><\/pre>\n\n\n\n

1.1. Method Parameters<\/h4>\n\n\n\n
  1. value<\/strong> (required) – The JavaScript object which needs to be converted to a JSON string.<\/li>
  2. replacer<\/strong> (optional) – The function that alters the behavior of the stringification process. If replace function is not provided, all properties of the object are included in the resulting JSON string.<\/li>
  3. space<\/strong> (optional) – For indentation purpose. A String or Number that’s used to insert whitespaces into the output JSON string for readability purposes.\n

    If this is a Number, it indicates the number of space characters to use as whitespace.<\/p>\n<\/li><\/ol>\n\n\n\n

    2. JSON.stringify() Example<\/h2>\n\n\n\n
    console.log( JSON.stringify({ x: 5, y: 6 }) );\r\nconsole.log( JSON.stringify({ x: 5, y: 6 }, null, ' ') ); \/\/with space<\/code><\/pre>\n\n\n\n

    Program output.<\/p>\n\n\n\n

    {\"x\":5,\"y\":6}\r\n\r\n{\r\n\"x\": 5,\r\n\"y\": 6\r\n}<\/code><\/pre>\n\n\n\n

    3. JSON.stringify() Replacer Function Example<\/h2>\n\n\n\n
    var unmaskedData = { \"name\":\"Lokesh\", \"accountNumber\":\"3044444444\", \"city\":\"New York\"};\r\n\r\nvar maskedData = JSON.stringify( unmaskedData, maskInfo );\r\n\r\nfunction maskInfo (key, value) {\r\n\tvar maskedValue = value;\r\n\tif (key == \"accountNumber\")\r\n\t{\r\n\t\tif(value &amp;&amp; value.length &gt; 5) {\r\n\t\t\tmaskedValue = \"*\" + maskedValue.substring(value.length - 4, value.length);\r\n\t\t} else {\r\n\t\t\tmaskedValue = \"****\";\r\n\t\t}\r\n\t}\r\n\treturn maskedValue;\r\n}<\/code><\/pre>\n\n\n\n

    Program output.<\/p>\n\n\n\n

    {\r\n\"name\": \"Lokesh\",\r\n\"accountNumber\": \"*4444\", \/\/Masked account number\r\n\"city\": \"New York\"\r\n}<\/code><\/pre>\n\n\n\n

    Read More: Replacer function usage<\/a><\/p>\n\n\n\n

    4. Handling undefined values<\/h2>\n\n\n\n

    JSON.stringify()<\/code> does one of the following with an undefined value:<\/p>\n\n\n\n