JSON stands for JavaScript Object Notation used to structure data based on JavaScript object syntax. It is small in size making it fast to transfer between server and client for transmission of information.
JSON is based on JavaScript but due to its capability, it is implemented by many other programming languages like C, PHP, Python, etc.
A JSON string is a string containing JSON that is needed to change in another form that can operate by JavaScript and since the objects are best suited for JavaScript, it is recommended to convert a JSON String to a JavaScript Object before performing any operations.
There can be many ways to convert a JSON string to a JavaScript object using Node.js, but we will see the most reliable method for this which is the JSON.parse() method.
Also Read: NodeJS Convert String To Int – A Step-by-Step Guide
Structure of JSON String
The structure of JSON is simpler and easy to read by humans. Below is a JSON string containing two keys, name and age, along with their value.
const JSONString = `{
"fullname": "Stardew Valley",
"age": 30
}`;
Here we are using backticks (template literals) in place of quotation marks which are commonly used for string representation. We use backticks to avoid invalid JSON string errors that can occur when we define a string using single quotes or double quotes and do not escape the corresponding quotes inside that string properly. Additionally, the template allows multiline strings without literal line breaks.
Structure of JavaScript Object
Below is a JavaScript object with the same key-value pairs as above.
const javascriptObject = {
fullName: 'Stardew Valley',
age: 30
}
Difference Between JSON String and JavaScript Object
In JSON string the keys and value are wrapped inside double quotes (“), whereas in JavaScript object it is not required to wrap the key and value inside double quotes instead you can write the key without having any type of quotation marks and wrap the value if it is a string inside single or double quotes.
There is an exception that if the key contains special characters such as dashes (-), it must be wrapped inside single quotes (‘) to make it a valid JavaScript object.
const javascriptObject = {
fullName: 'Stardew Valley',
age: 30,
'is-vegetarian': true,
}
Convert JSON String to JavaScript Object Using JSON.parse()
There is a method JSON.parse() that can convert a JSON string to an object literals in JavaScript. This method takes a JSON string as an argument, converts the string into an object, and returns it.
Syntax of JSON.parse()
JSON.parse(JSONString[, optionalFunction]);
Parameters:
- JSONString is a JSON string to be converted into a JSON object,
- optionalFunction is an optional parameter. It is a callback function that is implemented on each pair of objects. This can be used to change or update values or filter results during parsing.
Example:
We have a JSON string containing multiple values and arrays.
const JSONString = `{
"fullname": "Stardew Valley",
"age": 30,
"is-vegetarian": true,
"hobbies": ["farming", "fishing", "mining", "foraging", "fighting"],
"address": {"street": "123 Main St", "city": "Pelican Town", "state": "California", "zip": "12345"},
"phone-numbers": [{"type": "home", "number": "123-456-7890"}, {"type": "work", "number": "123-456-7890"}]
}`;
Pass this as an argument to JSON.parse() method to convert it into a JavaScript Object.
const javascriptObject = JSON.parse(JSONString);
Print the returned Object in the console.
console.log(javascriptObject);
Complete Code to Convert JSON to JavaScript Object
const JSONString = `{
"fullname": "Stardew Valley",
"age": 30,
"is-vegetarian": true,
"hobbies": ["farming", "fishing", "mining", "foraging", "fighting"],
"address": {"street": "123 Main St", "city": "Pelican Town", "state": "California", "zip": "12345"},
"phone-numbers": [{"type": "home", "number": "123-456-7890"}, {"type": "work", "number": "123-456-7890"}]
}`;
const javascriptObject = JSON.parse(JSONString);
console.log(javascriptObject);
Output:
{
fullname: 'Stardew Valley',
age: 30,
'is-vegetarian': true,
hobbies: [ 'farming', 'fishing', 'mining', 'foraging', 'fighting' ],
address: {
street: '123 Main St',
city: 'Pelican Town',
state: 'California',
zip: '12345'
},
'phone-numbers': [
{ type: 'home', number: '123-456-7890' },
{ type: 'work', number: '123-456-7890' }
]
}
Here you can see that the return value is an object meaning we have successfully converted JSON string into a JavaScript object.
Handling Error
It may be possible that the string you are trying to convert is not a valid JSON string and hence it may cause unexpected behaviour of the code making error handling necessary, let’s see how.
Example:
const JSONString = 'Hello World!';
try {
const javascriptObject = JSON.parse(JSONString);
console.log(javascriptObject);
} catch (error) {
console.log("Please insert a valid JSON string");
}
Here the given string is not a valid JSON string so the code inside the catch block will be executed. You can take more control over the program by writing your own code in catch block.
Output:
Please insert a valid JSON string
Convert JavaScript Object To JSON String Using JSON.stringify()
In case you want, you can convert the JavaScript object back to a JSON-formatted string using another special method, JSON.stringify().
Example:
const javascriptObject = {
fullname: 'Stardew Valley',
age: 30,
'is-vegetarian': true,
hobbies: ['farming', 'fishing', 'mining', 'foraging', 'fighting'],
address: {
street: '123 Main St',
city: 'Pelican Town',
state: 'California',
zip: '12345'
},
'phone-numbers': [
{ type: 'home', number: '123-456-7890' },
{ type: 'work', number: '123-456-7890' }
]
};
const JSONString = JSON.stringify(javascriptObject);
console.log(JSONString);
Output:
{
"fullname": "Stardew Valley",
"age": 30,
"is-vegetarian": true,
"hobbies": ["farming", "fishing", "mining", "foraging", "fighting"],
"address": {
"street": "123 Main St",
"city": "Pelican Town",
"state": "California",
"zip": "12345"
},
"phone-numbers": [
{"type": "home", "number": "123-456-7890"},
{"type": "work", "number": "123-456-7890"}
]
}
We got the same result from where we started.
Read More: Send a JSON response using Express Framework
Summary
JavaScript uses objects everywhere, and performing operations on it is easier than other forms of data structures. A JSON is also based on JS object structure, it is smaller in size and easily understandable. It is used to store data and transmission data from server to client.
JSON is used by many other programming languages which can parse it into a format that they can understand. Since JavaScript performs well with objects, it is recommended to convert a string into a JavaScript object in Node.js before performing any further operations. This can be easily done using a method JSON.parse() that takes a JSON string as an argument and returns a JavaScript object. Hope this tutorial helps you convert string to object in JavaScript.
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse