JSON is a special data structure that allows you to easily convert a specific object or a value to a string format. It's very widely used in web programming. You may store JSON data in a database, save on disk or send via network to the other computer.
This guide shows how to parse a JSON structure and convert it back to the object. That is needed if you'd like to manipulate or analyze the data. Please review the following sections to learn how exactly it can be done in JavaScript.
Table of Contents
- Using the JSON.parse() method
- Parsing a single JavaScript object
- Parsing an array of string values
- Parsing an array of objects
- Transforming a single value during JSON conversion
- Parsing a date
- Handling errors that may occur during JSON conversion
- How to parse a JSON in TypeScript
- Parsing object in TypeScript that may have optional properties
- Parsing object in TypeScript that may have union types
- Using type assertion to verify the converted object
- Using the Request.json() method to parse the JSON data
- Conclusion
Using the JSON.parse() method
JavaScript provides the static JSON.parse()
method. To use it, you have to pass at least a single argument, which is the string to parse. The specification is shown below.
JSON.parse(text)
This method will return a regular JavaScript value that can be used in your code. It can be object, number or other built-in JavaScript type. The actual type is determined by the data that is stored in the given string.
Also, the JSON.parse()
method accepts a second parameter. It allows you to specify a special function that can modify each value on the fly. This option may be used if your data has to be converted to a specific format.
Below, you can see the full specification of this method.
JSON.parse(text, callback)
Also, the following is an example of the callback that may be passed into the JSON.parse()
method.
function jsonCallback(jsonKey, jsonValue) {
return NEW_VALUE;
}
Although, you may need to improve that callback. Likely, you'll want to add some conditional statements there. That is needed to return new values only in specific cases.
Parsing a single JavaScript object
Let's test the JSON.parse()
method and see how it works. In the following sample, we've prepared a string value that contains a serialized object. Then, that string is parsed and converted back into the JavaScript object. Finally, the returned value is printed to the console.
const jsonValue = '{"type":"product", "title":"Computer mice", "price":29, "weight":200}';
const parsedObject = JSON.parse(jsonValue);
console.log(parsedObject);
The console output of the given demo is shown below. As you may see, the object was successfully parsed.
developer@developer-pc:~/samples/javascript$ node index.js
{ type: 'product', title: 'Computer mice', price: 29, weight: 200 }
Parsing an array of string values
The following sample is similar to the previous one. The only modification is that it tests a JSON string that contains an array of string values. We'd like to see if that value is correctly parsed and printed to the screen. See the code sample below.
const jsonValue = '["Apple", "Strawberry", "Grape", "Pear", "Watermelon"]';
const parsedArray = JSON.parse(jsonValue);
console.log(parsedArray);
Now, we can run it and see what the console output is.
developer@developer-pc:~/samples/javascript$ node index.js
[ 'Apple', 'Strawberry', 'Grape', 'Pear', 'Watermelon' ]
Parsing an array of objects
The same way, we can test that the array of objects is correctly parsed by the JSON.parse()
method. We only need to specify the correct string for the jsonValue
variable. See how it is done below.
const jsonValue = '[{"count":17, "price":29}, {"count":25, "price":39}]';
const parsedObject = JSON.parse(jsonValue);
console.log(parsedObject);
If you run the given code, the console output would be like the following.
developer@developer-pc:~/samples/javascript$ node index.js
[ { count: 17, price: 29 }, { count: 25, price: 39 } ]
Transforming a single value during JSON conversion
As we've already mentioned, the JSON.parse()
method allows you to provide a callback. It can be used to replace specific values in your JSON data.
The following sample shows how exactly this feature works. There, we check the name of the key. If it's a type
, then we replace the given value by the word device.
const jsonValue = '{"type":"product", "title":"Computer mice", "price":29, "weight":200}';
const parsedObject = JSON.parse(jsonValue, (key, value) => {
if (key === 'type') {
return 'device';
}
return value;
});
console.log(parsedObject);
Let's test the given code. It should print the modified object to the terminal, as shown below.
developer@developer-pc:~/samples/javascript$ node index.js
{ type: 'device', title: 'Computer mice', price: 29, weight: 200 }
Parsing a date
JSON string may have the date saved as a regular Unix timestamp. That format is not human friendly since the actual date value is saved as a number. However, if you'd like to read the date in human form, then you have to convert it.
Manually parsing a date value
The simplest method is to convert value for a specific field. That method is acceptable when you have a small object and you need to quickly see the date that is saved in the JSON string. See how it can be done in the following code sample.
const jsonValue = '{"type":"product", "created_at":1691417421000, "title":"Computer mice", "price":29}';
const parsedObject = JSON.parse(jsonValue);
parsedObject.created_at = new Date(parsedObject.created_at);
console.log(parsedObject);
If you run the given code, you should see the date value in a string format. Example is shown below.
developer@developer-pc:~/samples/javascript$ node index.js
{
type: 'product',
created_at: 2023-08-07T14:10:21.000Z,
title: 'Computer mice',
price: 29
}
Parsing a date value on a fly
However, the above method has a huge disadvantage. JSON data may contain many objects inside. And each of those objects may have a complex structure. In that case, you'll have to write a lot of code to manually replace each value.
To solve that issue, you may create a special callback that will process each field on a fly. If that callback detects that there is a date, then it can parse it with help of the Date
object.
The following sample shows how it may be implemented in your project.
const jsonValue = '{"type":"product", "created_at":1691417421000, "title":"Computer mice", "price":29}';
const parsedObject = JSON.parse(jsonValue, (key, value) => {
if (key === 'created_at') {
return new Date(value);
}
return value;
});
console.log(parsedObject);
Please run the given code sample with help of the NodeJS tool. There should be a correct date in the console output.
developer@developer-pc:~/samples/javascript$ node index.js
{
type: 'product',
created_at: 2023-08-07T14:10:21.000Z,
title: 'Computer mice',
price: 29
}
Handling errors that may occur during JSON conversion
If the JSON string is not valid, then the JSON.parse()
method may throw an exception. In most cases, it's better to handle such situations in your project. There are many reasons why the JSON can be broken, such as network error, invalid symbols or simply a bug in the code.
Your application may catch such errors with help of the try/catch
block. See our code sample below. It shows how it can be done.
try {
JSON.parse(jsonValue);
} catch(error) {
console.error(error);
}
How to parse a JSON in TypeScript
TypeScript allows us to add type-safety into your application. We can make a code that is more stable and is well-tested. If you are using the JSON.parse()
method, then that type-safety has to be taken into the account.
We've created a very simple demo that shows how it can be done. Our code contains the Product
interface. It defines the structure of our object.
After the object is parsed, we assign it to the parsedProduct
variable, which implements the Product
interface. Later, it allows us to access properties of that object with help of the dot syntax.
interface Product {
title: string;
price: number;
}
const jsonValue: string = '{"title":"Computer mice", "price":29}';
const parsedProduct: Product = JSON.parse(jsonValue);
console.log('Title:', parsedProduct.title);
console.log('Price:', parsedProduct.price);
The above code is a TypeScript application. This means that it has to be executed with a special tool that can compile the TypeScript code. In our case, we'll use the ts-node
utility, as shown below.
developer@developer-pc:~/samples/typescript$ npx ts-node index.ts
Title: Computer mice
Price: 29
Parsing object in TypeScript that may have optional properties
Earlier, we described how to parse an object that has mandatory fields. However, you may also have optional properties in your object. In that case, the code would not be so much different. You only have to properly define your interface. The question mark should be added to the specification of the properties that are optional.
Please see how it has to be done in the following example.
interface Product {
title: string;
price: number;
category?: string;
}
const jsonValue: string = '{"title":"Computer mice", "price":29}';
const parsedProduct: Product = JSON.parse(jsonValue);
console.log('Title:', parsedProduct.title);
console.log('Price:', parsedProduct.price);
console.log('Category:', parsedProduct.category);
Let's run our code sample and see how it works. The console output should be like the following.
developer@developer-pc:~/samples/typescript$ npx ts-node index.ts
Title: Computer mice
Price: 29
Category: undefined
Parsing object in TypeScript that may have union types
The same way, we can define an interface that has optional union types. You only need to properly configure the desired fields.
See our code sample below. We've added the question mark to the category
property, which can be of either string
or number
type.
interface Product {
title: string;
category?: string | number;
}
const jsonValue: string = '{"title":"Computer mice", "category":777}';
const parsedProduct: Product = JSON.parse(jsonValue);
console.log('Title:', parsedProduct.title);
console.log('Category:', parsedProduct.category);
If you run the given code, the console output should be like the following.
developer@developer-pc:~/samples/typescript$ npx ts-node index.ts
Title: Computer mice
Category: 777
Using type assertion to verify the converted object
We've defined how our objects may look. However, there is a chance that some object contains invalid data. You may expect some field to be a string, but the actual object may contain a number.
There is a method that can help you to ensure that each field is correct. You may write a function that will test that each field is of the correct type. Please see below how it may be implemented in your application.
interface Product {
title: string;
price: number;
}
function isProductValid(product: Product) {
if (typeof parsedProduct.title !== 'string') {
return false;
}
if (typeof parsedProduct.price !== 'number') {
return false;
}
return true;
}
const jsonValue: string = '{"title":"Computer mice", "price":29}';
const parsedProduct: Product = JSON.parse(jsonValue)
if (isProductValid(parsedProduct)) {
console.log('Product is valid');
} else {
console.log('Product is not valid');
}
Now, let's try the given code. It should produce output like it's shown below.
developer@developer-pc:~/samples/typescript$ npx ts-node index.ts
Product is valid
Using the Request.json() method to parse the JSON data
There is an alternative method that allows us to convert JSON string to an object. If you are obtaining data from the network, then you can use the Request.json()
method. It may parse the string that is returned by the fetch()
method.
The correct usage is shown below. However, you may need to change the URL for the API. The following code is just an example that has to be modified according to your needs.
const jsonRequest = await fetch('https://example.com/products');
const parseProducts = await jsonRequest.json();
console.log(parseProducts);
Conclusion
As you see, it's easy to parse JSON data in JavaScript or TypeScript. You can use the JSON.parse()
method for that purpose. That is a standard built-in function that is supported in most browsers. Also it's available in the NodeJS runtime environment.
However, it's important to remember that the JSON.parse()
method may throw exceptions. It can occur if the JSON data is not valid. And to make a stable code, you may consider adding the try/catch
section to your code.
Thanks for sharing this information. I've been struggling with parsing JSON in my projects, but your article made it much clearer.