最早接触 JSON 时,是在使用 Python 爬虫的过程中。例如,当我们在爬取豆瓣电影 Top 250 时,返回的数据格式正是 JSON。在爬虫框架中,我们还常常使用 yield 将数据以 JSON 的形式输出。
My first encounter with JSON was while working on Python web scraping projects. For instance, when scraping the IMDb Top 250 movies from Douban, the returned data was in the JSON format. In web scraping frameworks, we often use the yield keyword to output data in JSON format.
当我开始恶补 JavaWeb 时,又一次在前端里看到了熟悉的 JSON。这才第一次了解到 JSON 的全称是 JavaScript Object Notation,即 JavaScript 对象标记法。
As I embarked on a journey to delve into JavaWeb, I encountered a familiar friend within the realm of frontend development: JSON. It was during this exploration that I learned for the first time that JSON’s full name is “JavaScript Object Notation,” also known as “JavaScript Object Markup.”
所以才了解到:
JSON 最初由 Douglas Crockford 于 2001 年提出,他在 Yahoo! 工作期间发明了 JSON 作为一种用于配置文件的轻量级数据格式。
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,以易于人类阅读和编写的方式表示结构化数据。它采用键值对的形式,类似于字典或哈希表,每个键都是字符串,对应的值可以是字符串、数字、布尔值、数组,甚至是嵌套的对象。JSON 的设计灵感来源于 JavaScript 对象字面量,但它是一种与编程语言无关的格式,适用于多种编程语言和场景。
JSON was originally introduced by Douglas Crockford in 2001 during his time at Yahoo! He invented JSON as a lightweight data format for configuration files.
JSON (JavaScript Object Notation) is a lightweight data interchange format that represents structured data in a human-readable and writable format. It uses key-value pairs, similar to dictionaries or hash tables. Each key is a string, and its corresponding value can be a string, number, boolean, array, or even nested objects. JSON draws inspiration from JavaScript object literals, but it is a language-independent format that works with various programming languages and scenarios.
有以下优势:
- 易于理解和编写: JSON 的格式类似于 JavaScript 对象,因此它易于人类理解和编写。这种特性使得开发人员能够轻松创建和读取 JSON 数据。
- 易于解析和生成: 多数编程语言都提供了 JSON 解析和生成的库,这使得操作 JSON 数据变得非常简单。数据在不同编程语言之间的传递变得更加方便。
- 广泛的应用场景: JSON 在许多不同的应用场景中得到了应用,包括 Web 开发、API 通信、移动应用程序等。它已成为数据交换的通用选择。
It has several advantages:
- Easy to understand and write: JSON’s format resembles JavaScript objects, making it easy for humans to understand and write. This feature allows developers to effortlessly create and read JSON data.
- Easy to parse and generate: Most programming languages offer libraries for parsing and generating JSON, simplifying the manipulation of JSON data. Data interchange between different programming languages becomes more convenient.
- Wide range of applications: JSON finds applications in various scenarios, including web development, API communication, mobile applications, and more. It has become a universal choice for data exchange.
JSON 已然成了每一种编程语言都要去实现的、跨编程语言数据交换的通用标准。下面我们来看一下几种典型的编程语言是如何处理 JSON 和字符串格式之间的转换的。
JSON has become a universally adopted standard across programming languages for data exchange, necessitating implementation in every language. Let’s delve into how several typical programming languages handle the conversion between JSON and string formats.
JavaScript:
1. 解析 JSON 字符串为 JavaScript 对象 (JSON.parse()):
var jsonString = '{"name": "Tom", "age": 20}';
var jsonObject = JSON.parse(jsonString);
2. 转换 JavaScript 对象为 JSON 字符串 (JSON.stringify()):
var jsonObject = { name: "Tom", age: 20 };
var jsonString = JSON.stringify(jsonObject);
Python:
1. 解析 JSON 字符串为 Python 对象 (json.loads()):
import json
json_string = '{"name": "Tom", "age": 20}'
python_object = json.loads(json_string)
2. 转换 Python 对象为 JSON 字符串 (json.dumps()):
import json
python_object = {'name': 'Tom', 'age': 20}
json_string = json.dumps(python_object)
Golang:
1. 解析 JSON 字符串为 Golang 结构体 (json.Unmarshal()):
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonBytes := []byte(`{"name": "Tom", "age": 20}`)
var person Person
err := json.Unmarshal(jsonBytes, &person)
if err != nil {
fmt.Println("Error:", err)
}
}
2. 转换 Golang 结构体为 JSON 字符串 (json.Marshal()):
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "Tom", Age: 20}
jsonBytes, err := json.Marshal(person)
if err != nil {
fmt.Println("Error:", err)
}
jsonString := string(jsonBytes)
}
Java:
1. 解析 JSON 字符串为 Java 对象 (Gson.fromJson()):
import com.google.gson.Gson;
class Person {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\": \"Tom\", \"age\": 20}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
}
}
2. 转换 Java 对象为 JSON 字符串 (Gson.toJson()):
import com.google.gson.Gson;
class Person {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Tom";
person.age = 20;
Gson gson = new Gson();
String jsonString = gson.toJson(person);
}
}
English Version:
JavaScript:
1. Parsing JSON String to JavaScript Object (JSON.parse()):
var jsonString = '{"name": "Tom", "age": 20}';
var jsonObject = JSON.parse(jsonString);
2. Converting JavaScript Object to JSON String (JSON.stringify()):
var jsonObject = { name: "Tom", age: 20 };
var jsonString = JSON.stringify(jsonObject);
Python:
1. Parsing JSON String to Python Object (json.loads()):
import json
json_string = '{"name": "Tom", "age": 20}'
python_object = json.loads(json_string)
2. Converting Python Object to JSON String (json.dumps()):
import json
python_object = {'name': 'Tom', 'age': 20}
json_string = json.dumps(python_object)
Golang:
1. Parsing JSON String to Golang Struct (json.Unmarshal()):
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonBytes := []byte(`{"name": "Tom", "age": 20}`)
var person Person
err := json.Unmarshal(jsonBytes, &person)
if err != nil {
fmt.Println("Error:", err)
}
}
2. Converting Golang Struct to JSON String (json.Marshal()):
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
person := Person{Name: "Tom", Age: 20}
jsonBytes, err := json.Marshal(person)
if err != nil {
fmt.Println("Error:", err)
}
jsonString := string(jsonBytes)
}
Java:
1. Parsing JSON String to Java Object (Gson.fromJson()):
import com.google.gson.Gson;
class Person {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\": \"Tom\", \"age\": 20}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
}
}
2. Converting Java Object to JSON String (Gson.toJson()):
import com.google.gson.Gson;
class Person {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Tom";
person.age = 20;
Gson gson = new Gson();
String jsonString = gson.toJson(person);
}
}
These examples demonstrate how to use JSON conversion methods in different programming languages to parse and serialize JSON data. Regardless of the programming language you choose, these methods allow you to easily transmit and manipulate data between different formats.
