Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Convert JavaScript Object to JSON String

#1
Convert JavaScript Object to JSON String

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/convert-javascript-object-to-json-string.jpg" width="550" height="391" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 26th, 2022.</div>
<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>
<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>
<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>
<h2>Quick example</h2>
<div class="post-section-highlight" readability="34">
<pre class="prettyprint"><code class="language-javascript">var jsObject = { "name": "Lion", "type": "wild"
};
var jsonString = JSON.stringify(jsObject)
console.log(jsonString);
</code></pre>
</div>
<p><strong>Output</strong></p>
<pre class="prettyprint"><code>{"name":"Lion","type":"wild"}
</code></pre>
<p><img 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/20...00x213.jpg 300w, https://phppot.com/wp-content/uploads/20...68x546.jpg 768w, https://phppot.com/wp-content/uploads/20...string.jpg 1012w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>About JavaScript JSON.stringify()</h2>
<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>
<h3>Syntax</h3>
<pre class="prettyprint"><code class="language-javascript">JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
</code></pre>
<p>The replacer and space parameters are optional.</p>
<ul>
<li><em>value</em> – The JS object to be converted to a JSON string.</li>
<li><em>replacer</em> – a&nbsp; function or an array of specifications to convert JavaScript objects.</li>
<li><em>space</em> – It is a specification used to format or prettify the output JSON.</li>
</ul>
<p>The JSON.stringify() method can also accept JavaScript arrays to convert into JSON strings.</p>
<h2>How to get a formatted JSON string from a JavaScript object</h2>
<p>This example supplies the “space” parameter to the JSON.stringify method. This parameter helped to format the JSON string as shown in the output below the program.</p>
<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>
<pre class="prettyprint"><code class="language-javascript">var jsObject = { "name": "Lion", "type": "wild"
}; // this is to convert a JS object to a formatted JSON string
var formattedJSON = JSON.stringify(jsObject, null, 2);
console.log(formattedJSON);
</code></pre>
<p><strong>Output</strong></p>
<pre class="prettyprint"><code>{ "name": "Lion", "type": "wild"
}
</code></pre>
<h2>How to store JSON string to a JavaScript localStorage</h2>
<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>
<p>In this example, we used this storage tool to keep the JSON string of cart session data.</p>
<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>
<p><strong>Note: </strong>JSON.stringify() can also accepts array to convert into a JSON string.</p>
<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>
<pre class="prettyprint"><code class="language-javascript">const cart = { cartItem: []
};
cart.cartItem.push({ product: "Watch", quantity: 3, unitPrice: 100 });
cart.cartItem.push({ product: "Smart Phone", quantity: 5, unitPrice: 600 }); // use case for converting JS object to a JSON string
// convert object to JSON string before storing in local storage
const cartJSONString = JSON.stringify(cart); localStorage.setItem("cartSession", JSON.stringify(cartJSONString)); // retrieving from local storage
let cartFromStorage = localStorage.getItem("cartSession");
const getCartItemFromSession = JSON.parse(cartFromStorage); console.log(getCartItemFromSession);
</code></pre>
<p><strong>Output</strong></p>
<pre class="prettyprint"><code>{ "cartItem": [ {"product":"Watch","quantity":3,"unitPrice":100}, {"product":"Smart Phone","quantity":5,"unitPrice":600} ]
}
</code></pre>
<h2>How dates in the JavaScript object behave during JSON stringify</h2>
<p>The JSON.stringify() function converts the JavaScript Date object into an equivalent date string as shown in the output.</p>
<p>The code instantiates the JavaScript Date() class to set the current date to a JS object property.</p>
<pre class="prettyprint"><code class="language-javascript">// when you convert a JS object to JSON string, date gets automatically converted
// to equivalent string form
var jsObject = { "name": "Lion", "type": "wild", today: new Date()
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);
</code></pre>
<p><strong>Output</strong></p>
<pre class="prettyprint"><code>{"name":"Lion","type":"wild","today":"2022-10-23T10:58:55.791Z"}
</code></pre>
<h2>How JSON stringify converts the JavaScript objects with functions</h2>
<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>
<p>The resultant JSON string will have the rest of the properties that have valid mapping.</p>
<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; }
};
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);
</code></pre>
<p><strong>Output</strong></p>
<pre class="prettyprint"><code>{"name":"Lion","type":"wild"}
</code></pre>
<h2><strong>JavaScript <em>toString()</em> limitations over JSON.stringify:&nbsp;</strong></h2>
<p>If the input JavaScript object contains a single or with a predictable structure, <em>toString()</em> can achieve this conversion.</p>
<p>It is done by iterating the JS object array and applying stringification on each iteration. Example,</p>
<pre class="prettyprint"><code class="language-javascript">let jsonString = { 'name': 'Lion', type: 'wild', toString() { return '{name: "${this.name}", age: ${this.type}}'; }
};
console.log(jsonString);
</code></pre>
<p>But, it is not an efficient way that has the probability of missing some properties during the iteration.</p>
<h2>Why and how to convert the JSON string into a JSON object</h2>
<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>
<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>
<pre class="prettyprint"><code class="language-javascript">//JavaScript object
const jsObject = { 'animal-name': 'Lion', animalType: 'wild', endangered: false
} //JSON object
{ "animal-name": "Lion", "animalType": "wild", "endangered": false
}
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/javascript/javascript-object-to-json.zip">Download</a></p>
<p> <!-- #comments --> </p>
<p> <a href="https://phppot.com/javascript/javascript-object-to-json/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/10/...on-string/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016