Appearance
JSON
JSON stands for JavaScript Object Notation, a data interchange format. Before JSON, XML was commonly used for data transmission. While XML is a plain text format suitable for data exchange, its complexity increases with various specifications like DTD, XSD, and XPath, making it challenging for developers.
In 2002, Douglas Crockford invented JSON to simplify data exchange for software engineers who were overwhelmed by XML. As a lightweight data format, JSON is essentially a subset of JavaScript, supporting the following data types:
- number: Same as JavaScript's number.
- boolean: JavaScript's true or false.
- string: JavaScript's string.
- null: JavaScript's null.
- array: JavaScript's array format
[]
. - object: JavaScript's object format
{ ... }
.
JSON mandates UTF-8 character encoding, ensuring multi-language support. Strings and object keys must use double quotes ""
.
JSON's simplicity led to its rapid adoption on the web, becoming an ECMA standard, with parsing libraries available in nearly all programming languages. JavaScript natively supports JSON parsing.
Serialization
To convert a JavaScript object to a JSON string, we serialize it:
javascript
let xiaoming = {
name: '小明',
age: 14,
gender: true,
height: 1.65,
grade: null,
'middle-school': '\"W3C\" Middle School',
skills: ['JavaScript', 'Java', 'Python', 'Lisp']
};
let s = JSON.stringify(xiaoming);
console.log(s);
For a more readable output, we can add parameters for indentation:
javascript
JSON.stringify(xiaoming, null, ' ');
This produces:
json
{
"name": "小明",
"age": 14,
"gender": true,
"height": 1.65,
"grade": null,
"middle-school": "\"W3C\" Middle School",
"skills": [
"JavaScript",
"Java",
"Python",
"Lisp"
]
}
To output only specific properties, pass an array:
javascript
JSON.stringify(xiaoming, ['name', 'skills'], ' ');
Result:
json
{
"name": "小明",
"skills": [
"JavaScript",
"Java",
"Python",
"Lisp"
]
}
We can also pass a function to process each key-value pair:
javascript
function convert(key, value) {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
}
JSON.stringify(xiaoming, convert, ' ');
This converts all string values to uppercase:
json
{
"name": "小明",
"age": 14,
"gender": true,
"height": 1.65,
"grade": null,
"middle-school": "\"W3C\" MIDDLE SCHOOL",
"skills": [
"JAVASCRIPT",
"JAVA",
"PYTHON",
"LISP"
]
}
To have precise control over serialization, define a toJSON()
method:
javascript
let xiaoming = {
name: '小明',
age: 14,
gender: true,
height: 1.65,
grade: null,
'middle-school': '\"W3C\" Middle School',
skills: ['JavaScript', 'Java', 'Python', 'Lisp'],
toJSON: function () {
return {
'Name': this.name,
'Age': this.age
};
}
};
JSON.stringify(xiaoming); // '{"Name":"小明","Age":14}'
Deserialization
To convert a JSON string back into a JavaScript object, use JSON.parse()
:
javascript
JSON.parse('[1,2,3,true]'); // [1, 2, 3, true]
JSON.parse('{"name":"小明","age":14}'); // {name: '小明', age: 14}
It can also handle JSON values:
javascript
JSON.parse('true'); // true
JSON.parse('123.45'); // 123.45
You can pass a function to modify parsed attributes:
javascript
let obj = JSON.parse('{"name":"小明","age":14}', function (key, value) {
if (key === 'name') {
return value + '同学';
}
return value;
});
console.log(JSON.stringify(obj)); // {"name":"小明同学","age":14}
Practice
Access the OpenWeatherMap API to view JSON data, extracting city and weather information:
javascript
let url = 'https://api.openweathermap.org/data/2.5/forecast?q=Beijing,cn&appid=800f49846586c3ba6e7052cfc89af16c';
fetch(url).then(resp => {
resp.json().then(data => {
let info = {
city: data.city.name,
weather: data.list[0].weather[0].main,
time: data.list[0].dt_txt
};
alert(JSON.stringify(info, null, ' '));
});
});