JSON is a lightweight data interchange format, easy for humans to read, and easy for machines to parse and generate.
The relationship between JavaScript objects and JSON is very close. In fact, JSON stands for JavaScript Object Notation (so imagine how close their relationship is 😉).
Working with JSON in JavaScript is a common task, as JSON is a widely used format in web applications and APIs for data interchange.
Therefore, let’s look at the methods we have to work with them.
JSON Structure
In JavaScript, JSON is represented as a text string that follows a structure similar to that of a JavaScript object or array, but in plain text format.
JSON uses a syntax similar to JavaScript objects, but there are some key differences:
- Keys must be enclosed in double quotes.
- Properties cannot be functions,
Symbols
, orundefined
values.
For example,
{
"name": "Luis",
"age": 30,
"skills": ["JavaScript", "Python", "Java"]
}
const person = {
name: "Luis",
age: 30,
skills: ["JavaScript", "Python", "Java"],
greet: function() { //... }
}
Property values can be strings, numbers, arrays, objects, true
, false
, or null
,
Conversion between Objects and JSON
JavaScript provides built-in methods to convert objects to JSON and vice versa: JSON.stringify()
and JSON.parse()
.
Object to JSON
To convert a JavaScript object to a JSON string, JSON.stringify()
is used. This method takes an object as an argument and returns its representation in JSON format.
const person = {
name: 'Juan',
age: 30,
city: 'Madrid'
};
const personJSON = JSON.stringify(person);
console.log(personJSON);
// Result: {"name":"Juan","age":30,"city":"Madrid"}
In this example, person
is a JavaScript object that is converted to a JSON string using JSON.stringify()
.
JSON.stringify()
cannot handle properties that are functions, undefined
, or symbols. If the object has these properties they will be omitted in the resulting JSON string.
JSON to an Object
To convert a JSON string to a JavaScript object, we use the JSON.parse()
method.
const personJSON = '{"name":"Juan","age":30,"city":"Madrid"}';
const person = JSON.parse(personJSON);
console.log(person);
// Result: { name: 'Juan', age: 30, city: 'Madrid' }
In this example, personJSON
is a JSON string that is converted to a JavaScript object using JSON.parse()
.
Errors when working with JSON
When converting JSON to objects using JSON.parse()
, errors may occur if we try to parse invalid JSON.
const invalidJson = 'notJSON';
try {
const object = JSON.parse(invalidJson);
console.log(object);
} catch (error) {
console.error('Error parsing JSON:', error.message);
}
// Result: Error parsing JSON: Unexpected token o in JSON at position 0
In this example, invalidJson
is not a valid JSON string, so JSON.parse()
will throw an error that we can catch and handle.