To parse a JSON string in Node.js, you can use the JSON.parse()
function. This function takes a JSON string as an argument and returns a JavaScript object or array constructed from the JSON string.
Here’s an example of how to parse a JSON string:
const jsonString = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: "John"
In this example, we parse a JSON string that represents an object with three properties: name
, age
, and city
. After parsing the string with the JSON.parse()
function, we access the name
property of the resulting object using dot notation.
You can also use the JSON.parse()
function to parse a JSON array:
const jsonString = '[{"name":"John","age":30,"city":"New York"},{"name":"Jane","age":25,"city":"Chicago"}]';
const arr = JSON.parse(jsonString);
console.log(arr[0].name); // Output: "John"
In this example, we parse a JSON string that represents an array of objects, each with three properties: name
, age
, and city
. After parsing the string with the JSON.parse()
function, we access the name
property of the first element in the array using array notation.
Note: The JSON.parse()
function can throw a SyntaxError
if the JSON string is invalid. To handle this, you can use a try-catch block:
try {
const obj = JSON.parse(jsonString);
// Do something with the object
} catch (err) {
console.error(`Error parsing JSON string: ${err}`);
}