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.
Revisiting Objects & Strings in JavaScript
Before moving forward, we should know what objects & strings are and how they behave in JavaScript.
Just like we use hashmaps in C++ that store data in the form of “key-value” pairs, We use Objects in Javascript to store data in the same way, i.e. in the form of key-value pairs.
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.
For example, we have defined an object “car” with various properties below:
let car = {
name: "WagonR",
model: 2015,
price: 340000
};
Several properties such as name, model, and price are defined for the object “car”. The name, model, and price here indicate the keys, and “WagonR”, 2015 and 340000 are the values corresponding to the related keys.
On, the other hand, Strings in JavaScript represent a sequence of multiple characters. ‘C’ represents a single character and “Cat” represents a string.
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:
//declaring a string literal let a="FavTutor" //printing the string console.log(a);
Output:
FavTutor
Now, we can move forward to do the conversion from string to object.
JSON.parse() to Convert String to Object in JS
Whether it’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.
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.
Let us see an example of the same:
//declaring a string let str='{"name":"Josh","age":17}' //using the json.parse() method let objFromStr=JSON.parse(str); //printing the object console.log(objFromStr);
Output:
{ name: 'Josh', age: 17 }
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 “name” and “age”. The values corresponding to the keys are “Josh” and 17. Hence, we have converted the string to an object using the JSON.parse() method.
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’s look into the methods to deal with it.
Handling Dates in JSON
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.
Let’s take an example:
//declaring a string let str = '{"name":"Shawn", "age":17, "birthDate":"2003-01-15"}'; //parsing the string to object let objFromStr = JSON.parse(str) //converting the Date string to Date Object for(let key of Object.keys(objFromStr)){ if(key=="birthDate"){ objFromStr[key]=new Date(objFromStr[key]); } } //printing the object console.log(objFromStr)
Output:
{ name: 'Shawn', age: 17, birthDate: 2003-01-15T00:00:00.000Z }
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 “birthDate” 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;.
Handling Functions in JSON
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.
Here is an example:
// Original object with a function const myObject = { name: 'John', age: 30, myFunction: function() { return this.name + ' is ' + this.age + ' years old.'; } }; // Serialize the object while converting the function to a string representation const serializedObject = JSON.stringify(myObject, function(key, value) { if (typeof value === 'function') { return value.toString(); // Convert function to string } return value; }); console.log('Serialized Object:', serializedObject); // Parse the serialized JSON string back to an object const parsedObject = JSON.parse(serializedObject, function(key, value) { if (typeof value === 'string' && value.indexOf('function') === 0) { return new Function('return ' + value)(); // Create a function using Function constructor } return value; }); // Now you can call the function const result = parsedObject.myFunction(); console.log('Result of the function:', result); // Output: "John is 30 years old."
Output:
Serialized Object: {"name":"John","age":30,"myFunction":"function() {\r\n return this.name + ' is ' + this.age + ' years old.';\r\n }"}
Result of the function: John is 30 years old.
Now you can also learn how to convert String to Array in JavaScript, as it is also a common question asked in programming interviews.
Conclusion
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. If you still have any doubts, you might take our premium JavaScript homework help to clear them.