How to convert a string to JavaScript object?

In JavaScript, you can convert a JSON string to an object using the JSON.parse() method. This is commonly needed when working with API responses or stored data.

Syntax

JSON.parse(string)

Basic Example

<!DOCTYPE html>
<html>
<head>
    <title>String to Object Conversion</title>
</head>
<body>
    <h3>Original JSON String:</h3>
    <div id="jsonString">{"name":"Rohan", "sports":["Cricket","Football"], "country":"India"}</div>
    
    <h3>Converted Object Properties:</h3>
    <div id="result"></div>
    
    <button onclick="convertString()">Convert to Object</button>

    <script>
        function convertString() {
            let jsonString = '{"name":"Rohan", "sports":["Cricket","Football"], "country":"India"}';
            let parsedObject = JSON.parse(jsonString);
            
            let resultDiv = document.getElementById("result");
            resultDiv.innerHTML = `
                <p>Name: ${parsedObject.name}</p>
                <p>Country: ${parsedObject.country}</p>
                <p>Sports: ${parsedObject.sports.join(", ")}</p>
            `;
        }
    </script>
</body>
</html>

Error Handling

Always wrap JSON.parse() in a try-catch block to handle invalid JSON strings:

<!DOCTYPE html>
<html>
<head>
    <title>Safe JSON Parsing</title>
</head>
<body>
    <div id="output"></div>
    <button onclick="testParsing()">Test JSON Parsing</button>

    <script>
        function testParsing() {
            let validJson = '{"name":"Alice", "age":25}';
            let invalidJson = '{name:"Alice", age:25}'; // Missing quotes
            
            let output = document.getElementById("output");
            output.innerHTML = "";
            
            // Valid JSON
            try {
                let obj1 = JSON.parse(validJson);
                output.innerHTML += `<p>Valid: ${obj1.name}, Age: ${obj1.age}</p>`;
            } catch (error) {
                output.innerHTML += `<p>Error parsing valid JSON: ${error.message}</p>`;
            }
            
            // Invalid JSON
            try {
                let obj2 = JSON.parse(invalidJson);
                output.innerHTML += `<p>Invalid parsed successfully</p>`;
            } catch (error) {
                output.innerHTML += `<p>Error parsing invalid JSON: ${error.message}</p>`;
            }
        }
    </script>
</body>
</html>

Common Use Cases

Here are typical scenarios where you'll need to convert strings to objects:

<!DOCTYPE html>
<html>
<head>
    <title>JSON Conversion Use Cases</title>
</head>
<body>
    <div id="examples"></div>
    <button onclick="showExamples()">Show Examples</button>

    <script>
        function showExamples() {
            let examples = document.getElementById("examples");
            
            // API Response simulation
            let apiResponse = '{"status":"success", "data":{"users":3, "active":2}}';
            let parsedResponse = JSON.parse(apiResponse);
            
            // LocalStorage data
            let storageData = '{"theme":"dark", "language":"en", "notifications":true}';
            let userSettings = JSON.parse(storageData);
            
            // Configuration object
            let configString = '{"apiUrl":"https://api.example.com", "timeout":5000}';
            let config = JSON.parse(configString);
            
            examples.innerHTML = `
                <h4>API Response:</h4>
                <p>Status: ${parsedResponse.status}</p>
                <p>Total Users: ${parsedResponse.data.users}</p>
                
                <h4>User Settings:</h4>
                <p>Theme: ${userSettings.theme}</p>
                <p>Notifications: ${userSettings.notifications}</p>
                
                <h4>Configuration:</h4>
                <p>API URL: ${config.apiUrl}</p>
                <p>Timeout: ${config.timeout}ms</p>
            `;
        }
    </script>
</body>
</html>

Key Points

  • JSON.parse() converts valid JSON strings to JavaScript objects
  • The string must follow proper JSON format (double quotes, no trailing commas)
  • Always use try-catch to handle parsing errors gracefully
  • Commonly used with API responses, localStorage data, and configuration files

Conclusion

Use JSON.parse() to convert JSON strings to JavaScript objects. Always wrap it in try-catch blocks to handle invalid JSON gracefully and avoid runtime errors.

Updated on: 2026-03-15T23:18:59+05:30

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements