什么是 JSON(JavaScript 对象表示法)以及如何使用它

2025-06-07

什么是 JSON(JavaScript 对象表示法)以及如何使用它

对于编程新手来说,在刚开始的几周里,对各种缩写词感到困惑是很常见的。今天,我们将讨论一个在我们行业中非常常用的缩写词,相信我,它真的很容易理解!在本文中,我们将讨论 JSON 缩写的含义、用法、它是什么样子等等!请允许我介绍一下。

目录

JSON 到底是什么?

JSON或“JavaScript 对象表示法”只是 2000 年创建的一种用于传输数据的基本格式。但是当你看到这个名字时,你可能会问

如果是 JavaScript 对象表示法,那么我只能在 JavaScript 中使用它,对吗? - 你,2024

并非如此,因为它轻巧简单,因此其他语言也更容易阅读,更重要的是,人们也更容易阅读。

“好吧。如果这是一种轻松简单的数据传输方式,那么我会把它用作数据库。”——你,2024

我不推荐它....

为什么不呢?虽然 JSON 因其简洁易读的特性非常适合传输数据,但使用单个 JSON 文件作为整个数据库可能并非最佳选择。JSON 文件并非设计用于高效处理大量数据。它们缺乏 MySQL、PostgreSQL 等 SQL 数据库或 MongoDB 和 ScyllaDB 等 NoSQL 数据库的索引、查询和事务功能。使用单个 JSON 文件作为数据库可能会导致性能问题、数据完整性问题以及管理数据并发访问的挑战。

以前难道没有这样的数据传输方式吗?

当然有。主要使用的语言是 XML(可扩展标记语言),它被设计为一种灵活且可定制的标记语言。虽然它功能强大且高度可扩展,但它可能相当冗长。XML 中的每条数据都被标签包围,这会增加文件的大小和复杂性,尤其是在较大的文档或数据集中。

JSON 和 XML 有什么区别?

JSON 和 XML 都是数据序列化格式。JSON 更简洁,更易于阅读且解析速度更快,非常适合现代编程语言的数据结构。而 XML 则更加冗长,因为它使用了显式的开始和结束标记,支持更复杂的层次结构,非常适合需要详细元数据的应用程序。JSON 因其效率而成为 Web API 的首选,而 XML 则更适合需要大量文档标记的环境,例如企业应用程序。

下面是一个用于比较的 XML 示例:

<bookstore>   
    <book>     
        <title>Learning XML</title>     
        <author>Erik T. Ray</author>     
        <price>29.99</price>   
    </book>   
    <book>     
        <title>JSON for Beginners</title>     
        <author>iCode Academy</author>    
        <price>39.95</price>   
    </book> 
</bookstore>
Enter fullscreen mode Exit fullscreen mode

现在我们有了同样的例子,但这次是 JSON:

{
  "bookstore": {
    "books": [
      {
        "title": "Learning XML",
        "author": "Erik T. Ray",
        "price": 29.99
      },
      {
        "title": "JSON for Beginners",
        "author": "iCode Academy",
        "price": 39.95
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

XML 还值得一试吗?

嗯,这取决于你的目标是什么,但在我看来,总是值得看一看一些东西,即使你不打算使用它,只是为了了解它是什么以及它是如何使用的,你可能会遇到 XML 可以帮助你解决的问题,谁知道呢。

JSON 的优点

因此,正如您所见,使用 JSON 的主要原因是它的可读性,以及其他一些原因:

  • 易于阅读:JSON 具有清晰、直接的结构。
  • 易于解析:其简单的语法使计算机易于解析。
  • 紧凑:JSON 趋向于更轻量级,节省空间和带宽。
  • 通用:被各种编程语言和平台广泛支持,被谷歌和Twitter等大公司使用。

JSON 语法

JSON 语法很简单,没有太多秘密,遵循一些基本规则:

  1. 数据以名称/值对的形式存在:JSON 中的每个数据元素都表示为键(或名称)和值对,以冒号分隔。
  2. 数据以逗号分隔:对象内的多个键值对以逗号分隔。
  3. 花括号包含对象:JSON 中的对象括在花括号内{}
  4. 方括号包含数组:JSON 中的数组括在方括号内[]

但看起来比读起来更容易,所以这里有一些例子,以及每种类型的定义

JSON 数据类型

JSON 支持以下数据类型:

  • 字符串:用双引号括起来的字符序列。"name": "John Doe"
  • 数字:数值,可以是整数或浮点数。"age": 30
  • 对象:键值对的集合,用花括号括起来。"address": { "street": "123 Main St", "city": "Anytown" }
  • 数组:值的有序列表,用方括号括起来。"courses": ["Math", "Science", "History"]
  • 布尔值:真值或假​​值。"isStudent": false
  • Null:表示空值。"middleName": null

不,你不能在 JSON 中发表评论:D

汽车的实际例子

假设你想保存汽车及其详细信息的记录。以下是如何用 JSON 格式组织这些记录的示例:

{     
    "cars": [
        {         
            "brand": "Toyota",         
            "model": "Corolla",         
            "year": 2020,         
            "features": {             
                "color": "Blue",             
                "transmission": "Automatic"         
            }     
        }, 
        {         
            "brand": "Toyota",         
            "model": "Corolla",         
            "year": 2021,         
            "features": {             
                "color": "Red",             
                "transmission": "Automatic"         
            }     
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

如果您想添加更多汽车,您只需向 JSON 结构中的汽车数组添加更多对象即可。

这可以通过使用您选择的语言解析 JSON 然后根据需要对其进行操作来轻松完成,这里有一些使用前面显示的 JSON 的示例,可以让您更好地了解如何读取和解析 JSON 文件

在 JavaScript 中使用 JSON

const fs = require('fs').promises

const jsonPath = 'C:docs/example/example.json'
const readJsonFile = async () => {

    // Reads the content from the JSON and ensure is read as a string
    const jsonContent = await fs.readFile(jsonPath, 'utf-8')
    // Converts the JSON into a javascript object
    const data = JSON.parse(jsonContent)
    
    console.log(data.cars[0])
    //Output: { brand: "Toyota", model: "Corolla", year: 2020, features: { color: "Blue", transmission: "Automatic", }, }

    console.log(data.cars[1])
    //Output: { brand: "Toyota", model: "Corolla", year: 2021, features: { color: "Red", transmission: "Automatic", }, }

}
readJsonFile()
Enter fullscreen mode Exit fullscreen mode

在 Python 中使用 JSON

import json  

#Reads the JSON file  
with open('C:docs/example/example.json', 'r') as jsonFile:  
    #Parse the JSON content  
    jsonContent = json.load(jsonFile)  

print(jsonContent['cars'][0])  
#Output: {'brand': 'Toyota', 'model': 'Corolla', 'year': 2020, 'features': {'color': 'Blue', 'transmission': 'Automatic'}}  
print(jsonContent['cars'][1])  
#Output: {'brand': 'Toyota', 'model': 'Corolla', 'year': 2021, 'features': {'color': 'Red', 'transmission': 'Automatic'}}

Enter fullscreen mode Exit fullscreen mode

在 PHP 中使用 JSON

<?php  
$jsonPath = 'C:docs/example/example.json';  
// Reads the content from the JSON  
$contents = file_get_contents($jsonPath);  

// Converts the JSON content into a PHP Object  
$jsonContent = json_decode($contents);  

print_r($jsonContent->cars[1]);  
// Output: stdClass Object  
// (  
//    [brand] => Toyota  
//    [model] => Corolla  
//    [year] => 2021  
//    [features] => stdClass Object  
//        (  
//            [color] => Red  
//            [transmission] => Automatic  
//        )  
//  
//)
Enter fullscreen mode Exit fullscreen mode

在 Java 中使用 JSON

package org.example;  
import org.json.JSONArray;  
import org.json.JSONObject;  

import java.io.IOException;  
import java.nio.charset.StandardCharsets;  
import java.nio.file.Files;  
import java.nio.file.Paths;  

public class Main {  
    public static void main(String[] args) throws IOException {  
        String jsonFilePath = "C:docs/example/example.json";  
        // Reads the content from the file and converts into a string  
        String jsonContent = Files.readString(Paths.get(jsonFilePath), StandardCharsets.UTF_8);  

        // Converts the string content into a JSON Object  
        JSONObject jsonExample = new JSONObject(jsonContent);  

        JSONArray cars = jsonExample.getJSONArray("cars");  

        System.out.println(cars.get(0));  
        // Output: {"features": {"transmission":"Automatic","color":"Blue"},"year":2020,"model":"Corolla","brand":"Toyota"}  
        System.out.println(cars.get(1));  
        // Output: {"features":{"transmission":"Automatic","color":"Red"},"year":2021,"model":"Corolla","brand":"Toyota"}  

    }  
}
Enter fullscreen mode Exit fullscreen mode

PS:Java 示例使用json 库,如果您尝试它,请确保您的依赖项上有它。

结论

理解 JSON 乍一看可能有点棘手,但一旦掌握了窍门,其实就易如反掌了!我们介绍了什么是 JSON、如何使用它,以及它为何如此有用。

从理解它的语法到看到它在不同编程语言中的运行,您现在可以深入研究并开始在您的项目中使用 JSON。

如果您还有任何疑问,请直接问我。希望您喜欢这篇文章——别忘了点赞并分享给还在为 JSON 苦苦挣扎的朋友。

欢迎对本文提出反馈,以便我在下一篇中改进。感谢阅读,祝您健康,多喝水!

文章来源:https://dev.to/henriqueleme/what-is-json-javacript-object-notation-and-how-to-use-it-2mhk
PREV
无需 JavaScript 即可创建智能表单:HTML 和 AJAX 的魔力
NEXT
使用 GraphQL 创建模拟后端