Skip to content

Convert String to object JavaScript | Example code

  • by

The best solution to convert String to an object is using the JSON parse() method in JavaScript. Create a variable and use JSON.parse(“string”) to have it converted into an object.

JSON.parse(text[, reviver]);

Example String to object JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

   var string = '{"firstName":"name1", "age":30, "City":"NY"}';
   var myobj = JSON.parse(string);

   console.log(myobj);

  </script>

</body>
</html> 

Output:

Convert String to object JavaScript

If JSON string without the curly braces.

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);

console.log(obj);

Output: Object { firstName: “name1”, lastName: “last1” }

Converting a string with an array to an object:

var jsonString = '[1, 2, 3, 4, 5]';
var obj = JSON.parse(jsonString);

console.log(obj); // Output: [1, 2, 3, 4, 5]
console.log(obj[0]); // Output: 1
console.log(obj.length); // Output: 5

Converting a complex string with nested objects to an object:

var jsonString = '{"name": "John", "address": {"street": "123 Main St", "city": "New York"}}';
var obj = JSON.parse(jsonString);

console.log(obj);
console.log(obj.name); 
console.log(obj.address); 
console.log(obj.address.street); 

A string with boolean and null values to an object:

var jsonString = '{"isActive": true, "score": null}';
var obj = JSON.parse(jsonString);

console.log(obj); // Output: { isActive: true, score: null }
console.log(obj.isActive); // Output: true
console.log(obj.score); // Output: null

These examples demonstrate how JSON.parse() can be used to convert different types of strings into JavaScript objects. Remember to ensure that the string you are parsing is in valid JSON format, as JSON.parse() will throw an error if the string is malformed.

Comment if you have any doubts or suggestions on this JS Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *