{"id":129244,"date":"2022-10-26T10:40:59","date_gmt":"2022-10-26T10:40:59","guid":{"rendered":"https:\/\/phppot.com\/?p=19907"},"modified":"2022-10-26T10:40:59","modified_gmt":"2022-10-26T10:40:59","slug":"convert-javascript-object-to-json-string","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/10\/26\/convert-javascript-object-to-json-string\/","title":{"rendered":"Convert JavaScript Object to JSON String"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1304347826087\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on October 26th, 2022.<\/div>\n<p>JSON string conversion on the client and server side is an important requirement in data handling. Most programming languages contain native functions for <a href=\"https:\/\/phppot.com\/php\/json-handling-with-php-how-to-encode-write-parse-decode-and-convert\/\">handling JSON objects<\/a> and string data.<\/p>\n<p>The JSON format is a convenient way of structuring, transmitting, or logging hierarchical data. The JSON string is a bundled unit to transmit object properties over the API terminals.<\/p>\n<p>In this tutorial, we will see how to convert a JavaScript object to a JSON string. The JSON.stringify() of the JS script is used to do this. This is a quick solution for converting the given JS object to a JSON.<\/p>\n<h2>Quick example<\/h2>\n<div class=\"post-section-highlight\" readability=\"34\">\n<pre class=\"prettyprint\"><code class=\"language-javascript\">var jsObject = { \"name\": \"Lion\", \"type\": \"wild\"\n};\nvar jsonString = JSON.stringify(jsObject)\nconsole.log(jsonString);\n<\/code><\/pre>\n<\/div>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"prettyprint\"><code>{\"name\":\"Lion\",\"type\":\"wild\"}\n<\/code><\/pre>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19929\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/javascript-object-to-string-550x391.jpg\" alt=\"javascript object to string\" width=\"550\" height=\"391\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/javascript-object-to-string-550x391.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/javascript-object-to-string-300x213.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/javascript-object-to-string-768x546.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/javascript-object-to-string.jpg 1012w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>About JavaScript JSON.stringify()<\/h2>\n<p>The JSON.stringify() method accepts 3 parameters to convert JavaScript objects into JSON string. See the syntax and the possible parameters of this JavaScript method.<\/p>\n<h3>Syntax<\/h3>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">JSON.stringify(value)\nJSON.stringify(value, replacer)\nJSON.stringify(value, replacer, space)\n<\/code><\/pre>\n<p>The replacer and space parameters are optional.<\/p>\n<ul>\n<li><em>value<\/em> \u2013 The JS object to be converted to a JSON string.<\/li>\n<li><em>replacer<\/em> \u2013 a&nbsp; function or an array of specifications to convert JavaScript objects.<\/li>\n<li><em>space<\/em> \u2013 It is a specification used to format or prettify the output JSON.<\/li>\n<\/ul>\n<p>The JSON.stringify() method can also accept JavaScript arrays to convert into JSON strings.<\/p>\n<h2>How to get a formatted JSON string from a JavaScript object<\/h2>\n<p>This example supplies the \u201cspace\u201d parameter to the JSON.stringify method. This parameter helped to format the JSON string as shown in the output below the program.<\/p>\n<p>When we see the <a href=\"https:\/\/phppot.com\/php\/php-array-to-json\/\">PHP array to JSON conversion example<\/a>, it used the PHP bitmask parameter to achieve prettyprinting of JSON output.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">var jsObject = { \"name\": \"Lion\", \"type\": \"wild\"\n}; \/\/ this is to convert a JS object to a formatted JSON string\nvar formattedJSON = JSON.stringify(jsObject, null, 2);\nconsole.log(formattedJSON);\n<\/code><\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"prettyprint\"><code>{ \"name\": \"Lion\", \"type\": \"wild\"\n}\n<\/code><\/pre>\n<h2>How to store JSON string to a JavaScript localStorage<\/h2>\n<p>The <a href=\"https:\/\/phppot.com\/javascript\/javascript-localstorage\/\">localStorage is a mechanism to have persistent data<\/a> or state on the client side. It accepts string data to be stored with a reference of a user-defined key.<\/p>\n<p>In this example, we used this storage tool to keep the JSON string of cart session data.<\/p>\n<p>This code pushes two records to the cart array. Then, it converts the array into the JSON string to put it into the localStorage.<\/p>\n<p><strong>Note: <\/strong>JSON.stringify() can also accepts array to convert into a JSON string.<\/p>\n<p>We have already used this storage mechanism to <a href=\"https:\/\/phppot.com\/javascript\/javascript-shopping-cart\/\">create a JavaScript persistent shopping cart<\/a>.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">const cart = { cartItem: []\n};\ncart.cartItem.push({ product: \"Watch\", quantity: 3, unitPrice: 100 });\ncart.cartItem.push({ product: \"Smart Phone\", quantity: 5, unitPrice: 600 }); \/\/ use case for converting JS object to a JSON string\n\/\/ convert object to JSON string before storing in local storage\nconst cartJSONString = JSON.stringify(cart); localStorage.setItem(\"cartSession\", JSON.stringify(cartJSONString)); \/\/ retrieving from local storage\nlet cartFromStorage = localStorage.getItem(\"cartSession\");\nconst getCartItemFromSession = JSON.parse(cartFromStorage); console.log(getCartItemFromSession);\n<\/code><\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"prettyprint\"><code>{ \"cartItem\": [ {\"product\":\"Watch\",\"quantity\":3,\"unitPrice\":100}, {\"product\":\"Smart Phone\",\"quantity\":5,\"unitPrice\":600} ]\n}\n<\/code><\/pre>\n<h2>How dates in the JavaScript object behave during JSON stringify<\/h2>\n<p>The JSON.stringify() function converts the JavaScript Date object into an equivalent date string as shown in the output.<\/p>\n<p>The code instantiates the JavaScript Date() class to set the current date to a JS object property.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\/\/ when you convert a JS object to JSON string, date gets automatically converted\n\/\/ to equivalent string form\nvar jsObject = { \"name\": \"Lion\", \"type\": \"wild\", today: new Date()\n};\nconst jsonString = JSON.stringify(jsObject);\nconsole.log(jsonString);\n<\/code><\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"prettyprint\"><code>{\"name\":\"Lion\",\"type\":\"wild\",\"today\":\"2022-10-23T10:58:55.791Z\"}\n<\/code><\/pre>\n<h2>How JSON stringify converts the JavaScript objects with functions<\/h2>\n<p>If the JS object contains functions as a value of a property, the JSON.stringify will omit the function. Then, it will return nothing for that particular property.<\/p>\n<p>The resultant JSON string will have the rest of the properties that have valid mapping.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\/\/ when you convert a JS object to JSON string, \/\/ functions in JS object is removed by JSON.stringify var jsObject = { \"name\": \"Lion\", \"type\": \"wild\", age: function() { return 10; }\n};\nconst jsonString = JSON.stringify(jsObject);\nconsole.log(jsonString);\n<\/code><\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"prettyprint\"><code>{\"name\":\"Lion\",\"type\":\"wild\"}\n<\/code><\/pre>\n<h2><strong>JavaScript <em>toString()<\/em> limitations over JSON.stringify:&nbsp;<\/strong><\/h2>\n<p>If the input JavaScript object contains a single or with a predictable structure, <em>toString()<\/em> can achieve this conversion.<\/p>\n<p>It is done by iterating the JS object array and applying stringification on each iteration. Example,<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">let jsonString = { 'name': 'Lion', type: 'wild', toString() { return '{name: \"${this.name}\", age: ${this.type}}'; }\n};\nconsole.log(jsonString);\n<\/code><\/pre>\n<p>But, it is not an efficient way that has the probability of missing some properties during the iteration.<\/p>\n<h2>Why and how to convert the JSON string into a JSON object<\/h2>\n<p>The JSON string is a comfortable format during data transmission and data logging. Other than that it must be in a format of an object tree to parse, read from, and write to the JSON.<\/p>\n<p>The JSON.parse() method is used to convert JSON String to a JSON Object. A JSON object will look like a JS object only. See the following comparison between a JS object and a JSON object.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\/\/JavaScript object\nconst jsObject = { 'animal-name': 'Lion', animalType: 'wild', endangered: false\n} \/\/JSON object\n{ \"animal-name\": \"Lion\", \"animalType\": \"wild\", \"endangered\": false\n}\n<\/code><\/pre>\n<p><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/javascript\/javascript-object-to-json.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<p> <a href=\"https:\/\/phppot.com\/javascript\/javascript-object-to-json\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on October 26th, 2022. JSON string conversion on the client and server side is an important requirement in data handling. Most programming languages contain native functions for handling JSON objects and string data. The JSON format is a convenient way of structuring, transmitting, or logging hierarchical data. The JSON string is [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":129245,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-129244","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129244","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=129244"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129244\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/129245"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=129244"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=129244"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=129244"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}