How to Convert String to Object in JavaScript

To convert a String to an Object in JavaScript, you can “use the JSON.parse()” method. The JSON.parse() method is “used to parse a string and return an object.”

JavaScript JSON.parse()

The JSON.parse() method parses a string and returns an object. The JSON.parse() function takes one required and one optional parameter to perform some operation and returns an object.

Syntax

JSON.parse(string,function);

Parameters

  1. string:- It is a string that can be valid for any data type.
  2. function: It is an optional argument. We can pass this to our custom function if we want to perform some operation on our string.

Return value

The return value is based on what we pass in his parameter as a string. It generally returns an Object, but still, it depends on what you give as a string.

Example

const string = '{"name":"paresh","age":34,"professional":"coder"}';

const boolean = '{"isAdmin":true}';

const array = '["mango","banana","apple"]';

console.log(JSON.parse(string));
console.log(JSON.parse(boolean));
console.log(JSON.parse(array));

Output

{ name: 'paresh', age: 34, professional: 'coder' }
{ isAdmin: true }
[ 'mango', 'banana', 'apple' ]

In the above example, we pass a JSON string to the JSON.parse() method, and we get a JavaScript object in return. We also parse our array and a boolean value to its original form.

If you pass an array as a string to the JSON.parse() method, it returns an array. So let’s see how we give a function inside a JSON.parse() method to perform some operations on it.

const string = '{"name":"paresh","age":34,"professional":"coder"}';

console.log(JSON.parse(string, (key, value) => {
     return key === "age" ? `${value} year` : value;
}));

Output

{ name: 'paresh', age: '34 year', professional: 'coder' }

Here is an example of a string that is not in JSON format.

const string = 'Krunal is 30 years old and lives in Rajkot.';

try {
  const object = JSON.parse(string);
} catch (error) {
  console.log(error);
}

Output

SyntaxError: Unexpected token 'K', "Krunal is "... is not valid JSON

Manual convert String to object in JavaScript

const string = "name,paresh,age,34,professional,coder"

const temp = string.split(",");
const obj = {}
let i = 0;
while (i < temp.length) {
  obj[temp[i]] = temp[i + 1];
  i += 2;
}

console.log(obj)

Output

{ name: 'paresh', age: '34', professional: 'coder' }

In the above example, we have one string. So, firstly we split that string into an array using the string split() function. Then, we iterate that array and store that value in our object.

Conclusion

If you are working on a real-time project, the manual way is inefficient; instead, use the JSON.parse() method to convert your string to an object.

Related posts

JavaScript object to string

JavaScript Image to base64 string

JavaScript Boolean to String

Leave a Comment