JavaScript 6d ago 16 views 4 min read

How to parse a JSON string in JavaScript

Learn the exact methods to convert a JSON string into a usable JavaScript object using JSON.parse() and JSON.stringify().

Riya K.
Updated 22h ago
Sponsored

Cloud Hosting — blazing fast websites

Fully managed cloud hosting with free SSL, auto-backups and a friendly cPanel. Built for WordPress, Laravel and custom PHP apps.

You will learn how to convert a JSON-formatted string into a native JavaScript object using built-in functions. These steps apply to any modern browser or Node.js environment running JavaScript 2023 standards. You will handle parsing errors and validate data integrity.

Prerequisites

  • A code editor such as VS Code or Sublime Text
  • A modern browser like Chrome, Firefox, or Edge
  • Or a Node.js runtime (version 18.x or later)
  • Basic knowledge of JavaScript syntax and string literals

Step 1: Create a JSON string literal

Define a variable containing a valid JSON-formatted string. Ensure the string uses double quotes for keys and string values, as JSON specification requires double quotes and does not support single quotes.
const jsonString = '{"name": "Alice", "age": 30, "city": "New York"}';
You will see the string stored as a sequence of characters, not an object. The console or debugger will display the raw text with quotes.

Step 2: Parse the JSON string into an object

Use the global JSON.parse() method to convert the string into a JavaScript object. This function reads the string, validates the syntax, and returns a native object.
const user = JSON.parse(jsonString);
The resulting variable user is now a standard JavaScript object. You can access properties directly using dot notation or bracket notation.
console.log(user.name); // Output: Alice
console.log(user.age);  // Output: 30

Step 3: Handle invalid JSON strings

If the string contains a syntax error, JSON.parse() throws a SyntaxError. Wrap the parsing logic in a try-catch block to prevent your application from crashing.
const invalidJson = '{"name": "Bob", age: 25}'; // Missing quotes around key

try {
  const obj = JSON.parse(invalidJson);
} catch (error) {
  console.error(error.message);
  // Output: Unexpected token 'a' in JSON at position 4
}
You will see the error message in the console. This allows you to log the error, retry with corrected data, or show a user-friendly message.

Step 4: Parse JSON with nested structures

JSON supports arrays and nested objects. JSON.parse() handles these structures automatically without extra code.
const complexJson = '{"user": {"id": 1, "profile": {"name": "Charlie", "tags": ["dev", "js"]}}}'

const data = JSON.parse(complexJson);
console.log(data.user.profile.name); // Output: Charlie
console.log(data.user.profile.tags[1]); // Output: js
The nested properties are accessible just like any regular object. Arrays are treated as lists of values.

Step 5: Convert an object back to a JSON string

Use JSON.stringify() to serialize an object into a JSON string. This is useful for storing data in localStorage, sending it via fetch, or logging.
const userObj = {
  name: "Diana",
  age: 28,
  active: true
};

const jsonString = JSON.stringify(userObj);
console.log(jsonString);
// Output: {"name":"Diana","age":28,"active":true}
The output is a compact string. You can also format it with indentation using a replacer or space parameter.
const formattedJson = JSON.stringify(userObj, null, 2);
console.log(formattedJson);
// Output:
// {
//   "name": "Diana",
//   "age": 28,
//   "active": true
// }

Verify the installation

Since JSON.parse() is a built-in global function, no installation is required. To verify functionality, create a test file and run it in a browser console or Node.js REPL. Create a file named test-parse.js with this content:
const test = '{"key": "value"}';
const result = JSON.parse(test);
console.log(typeof result); // Output: "object"
console.log(result.key);   // Output: "value"
Run the file with Node:
node test-parse.js
You will see:
object
value
This confirms the global function works as expected.

Troubleshooting

Unexpected token error

Unexpected token 'a' in JSON at position 4
This occurs when a key or string value uses single quotes instead of double quotes. Fix by replacing 'key' with "key".

Trailing comma error

Unexpected token ',' in JSON at position 10
JSON does not allow trailing commas. Remove the comma after the last property: {"a": 1,} becomes {"a": 1}.

Undefined function error

JSON.parse is not a function
This happens in very old browsers or if the code runs in a non-HTML environment without proper scope. Ensure you are using a modern environment where JSON is globally available.

Invalid Unicode characters

Invalid Unicode escape
Ensure all non-ASCII characters are properly escaped or encoded as UTF-8 before parsing. Use encodeURIComponent for strings destined for JSON.

Best practices for JSON parsing

Always validate JSON before parsing when the source is untrusted. Use a schema validator like ajv for complex APIs. Never parse JSON from user input without sanitization. Store parsed objects in memory or databases, not as raw strings.
Sponsored

Windows Dedicated Server

High-performance Windows dedicated servers with licensed Windows Server, Remote Desktop access and enterprise-grade hardware.

Tags: JavaScriptJSONParsingData StructuresError Handling
0
Was this helpful?

Related tutorials

Comments 0

Login to leave a comment.

No comments yet — be the first to share your thoughts.