{"id":878,"date":"2023-12-09T13:00:00","date_gmt":"2023-12-09T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=878"},"modified":"2023-12-11T06:33:49","modified_gmt":"2023-12-11T06:33:49","slug":"convert-string-to-object-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/convert-string-to-object-javascript\/","title":{"rendered":"Convert String to Object in JavaScript (with JSON.Parse)"},"content":{"rendered":"\n<p>In the world of JavaScript programming, there often comes a time when we need to convert a string into an object. In this article, we will take a deep dive into how to convert string to object in JavaScript using the JSON Parse method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Revisiting Objects &amp; Strings in JavaScript<\/strong><\/h2>\n\n\n\n<p>Before moving forward, we should know what objects &amp; strings are and how they behave in JavaScript.\u00a0<\/p>\n\n\n\n<p>Just like we use hashmaps in C++ that store data in the form of \u201ckey-value\u201d pairs, We use Objects in Javascript to store data in the same way, i.e. in the form of key-value pairs.<\/p>\n\n\n\n<p>So, Objects are non-primitive data types in Javascript that store an unordered collection of key-value pairs. The association between key values is called property, so objects are a collection of properties.<\/p>\n\n\n\n<p>For example, we have defined an object \u201ccar\u201d with various properties below:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>let car = {\n    name: \"WagonR\",\n    model: 2015,\n    price: 340000\n};\n<\/code><\/pre>\n\n\n\n<p>Several properties such as name, model, and price are defined for the object \u201ccar\u201d. The name, model, and price here indicate the keys, and \u201cWagonR\u201d, 2015 and 340000 are the values corresponding to the related keys.<\/p>\n\n\n\n<p>On, the other hand, Strings in JavaScript represent a sequence of multiple characters. \u2018C\u2019 represents a single character and \u201cCat\u201d represents a string. <\/p>\n\n\n\n<p>We can declare a string in JavaScript by making a string literal using double quotes. The syntax and example for the same is given below:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring a string literal\nlet a=&quot;FavTutor&quot;\n\n\/\/printing the string\nconsole.log(a);<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>FavTutor<\/code><\/pre>\n\n\n\n<p>Now, we can move forward to do the conversion from string to object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>JSON.parse() to Convert String to Object in JS<\/strong><\/h2>\n\n\n\n<p>Whether it&#8217;s breaking down a sentence into individual words or splitting a string of characters, the ability to convert strings to objects is a crucial skill for any developer. <\/p>\n\n\n\n<p><strong>The best way to convert strings to objects in JavaScript is the JSON.parse() function. It parses a string containing JSON (JavaScript Object Notation) and converts it into a JavaScript object which further has key-value pairs.<\/strong><\/p>\n\n\n\n<p>Let us see an example of the same:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring a string\nlet str='{&quot;name&quot;:&quot;Josh&quot;,&quot;age&quot;:17}'\n\n\/\/using the json.parse() method\nlet objFromStr=JSON.parse(str);\n\n\/\/printing the object\nconsole.log(objFromStr);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>{ name: 'Josh', age: 17 }<\/code><\/pre>\n\n\n\n<p>The string that is passed in the JSON format is converted to an Object. We have printed the object. The keys of the object are \u201cname\u201d and \u201cage\u201d. The values corresponding to the keys are \u201cJosh\u201d and 17. Hence, we have converted the string to an object using the JSON.parse() method.<\/p>\n\n\n\n<p>Let us check out some problems that might occur while parsing strings to objects or the cases where the method is ambitious to use. Let\u2019s look into the methods to deal with it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Handling Dates in JSON<\/strong><\/h3>\n\n\n\n<p>Date Objects are not allowed in JSON. So, what if we need to include a date in your JSON data? To do that, we need to write the date object as a string. It can be converted back to the Date Object after the parsing.<\/p>\n\n\n\n<p>Let&#8217;s take an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring a string\nlet str = '{&quot;name&quot;:&quot;Shawn&quot;, &quot;age&quot;:17, &quot;birthDate&quot;:&quot;2003-01-15&quot;}';\n\n\/\/parsing the string to object\nlet objFromStr = JSON.parse(str)\n\n\/\/converting the Date string to Date Object\nfor(let key of Object.keys(objFromStr)){\n    if(key==&quot;birthDate&quot;){\n        objFromStr[key]=new Date(objFromStr[key]);\n    }\n}\n\n\/\/printing the object\nconsole.log(objFromStr)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>{ name: 'Shawn', age: 17, birthDate: 2003-01-15T00:00:00.000Z }<\/code><\/pre>\n\n\n\n<p>In this example, the string is first parsed into an Object. Then we loop over the object keys using the Object.keys() method and convert the value corresponding to the \u201cbirthDate\u201d key to a Date Object from Date String. We have obtained the desired result which is confirmed from the received output. The date has been converted to an object;.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Handling Functions in JSON<\/strong><\/h3>\n\n\n\n<p>JSON does not allow functions as object values either. To include a function in your JSON data, we should write it as a string. One disadvantage is that the functions lose their scope when converted to strings. They require additional steps to convert them back into functions.<\/p>\n\n\n\n<p>Here is an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Original object with a function\nconst myObject = {\n  name: 'John',\n  age: 30,\n  myFunction: function() {\n    return this.name + ' is ' + this.age + ' years old.';\n  }\n};\n\n\/\/ Serialize the object while converting the function to a string representation\nconst serializedObject = JSON.stringify(myObject, function(key, value) {\n  if (typeof value === 'function') {\n    return value.toString(); \/\/ Convert function to string\n  }\n  return value;\n});\n\nconsole.log('Serialized Object:', serializedObject);\n\n\/\/ Parse the serialized JSON string back to an object\nconst parsedObject = JSON.parse(serializedObject, function(key, value) {\n  if (typeof value === 'string' &amp;&amp; value.indexOf('function') === 0) {\n    return new Function('return ' + value)(); \/\/ Create a function using Function constructor\n  }\n  return value;\n});\n\n\/\/ Now you can call the function\nconst result = parsedObject.myFunction();\nconsole.log('Result of the function:', result); \/\/ Output: &quot;John is 30 years old.&quot;<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Serialized Object: {\"name\":\"John\",\"age\":30,\"myFunction\":\"function() {\\r\\n    return this.name + ' is ' + this.age + ' years old.';\\r\\n  }\"}\nResult of the function: John is 30 years old.\n<\/code><\/pre>\n\n\n\n<p>Now you can also learn how to <a href=\"https:\/\/favtutor.com\/articles\/string-to-array-javascript\/\">convert String to Array in JavaScript<\/a>, as it is also a common question asked in programming interviews.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this blog, we discussed the JSON.parse() method that helps in converting JSON string to object. We also dealt with problems that relate to Date and Functions.\u00a0\u00a0If you still have any doubts, you might take our premium <a href=\"https:\/\/favtutor.com\/javascript-assignment-help\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/javascript-assignment-help\">JavaScript homework help<\/a> to clear them.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to convert string to object in JavaScript using JSON Parse method. We also explored how to handle Date and Functions in JSON.<\/p>\n","protected":false},"author":9,"featured_media":883,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11,38],"class_list":["post-878","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript","tag-javascript-strings"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/878","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=878"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/878\/revisions"}],"predecessor-version":[{"id":919,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/878\/revisions\/919"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/883"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=878"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=878"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=878"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}