YAML文件的写法,以及和JSON的区别

2024-07-11  本文已影响0人  lihao_李浩

YAML(YAML Ain't Markup Language)基本规则与比较

YAML(YAML Ain't Markup Language)是一种人类可读的、用于数据序列化的格式。以下是一些基本的YAML书写规则:

基本规则

数据类型

1 字符串

name: John Doe
description: "A developer"
single_line: "This is a single line string"
multi_line: |
  This is a multi-line string.
  It can contain multiple lines.

2 数字

age: 30
height: 1.75

2 布尔值

is_active: true
has_account: false

3 列表

languages:
  - Python
  - JavaScript
  - Go

4 对象

address:
  street: 123 Main St
  city: Anytown
  zip: 12345

示例

以下是一个包含多种数据类型的完整YAML示例:

用户信息

user:
  name: John Doe
  age: 30
  is_active: true
  skills:
    - Programming
    - Writing
  address:
    street: 123 Main St
    city: Anytown
    zip: 12345
  profile:
    description: >
      John is a developer
      and writer.
    bio: |
      He works on various projects.
      Loves coding and sharing knowledge.

YAML 和 JSON 有许多相似之处,都是用于数据序列化的格式,并且在很多场景下可以相互转换。不过,它们在语法和使用上也有一些不同之处。以下是一些主要区别:

YAML 和 JSON 的区别

1 可读性

2 注释

3 格式要求

4 数据类型

示例对比

以下是相同数据在 YAML 和 JSON 中的表示形式:
YAML 示例

user:
  name: John Doe
  age: 30
  is_active: true
  skills:
    - Programming
    - Writing
  address:
    street: 123 Main St
    city: Anytown
    zip: 12345
  profile:
    description: >
      John is a developer
      and writer.
    bio: |
      He works on various projects.
      Loves coding and sharing knowledge.

JSON 示例

{
  "user": {
    "name": "John Doe",
    "age": 30,
    "is_active": true,
    "skills": [
      "Programming",
      "Writing"
    ],
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "zip": "12345"
    },
    "profile": {
      "description": "John is a developer and writer.",
      "bio": "He works on various projects.\nLoves coding and sharing knowledge."
    }
  }
}

适用场景

总的来说,YAML 和 JSON 各有优缺点,选择使用哪种格式取决于具体的使用场景和需求。

上一篇下一篇

猜你喜欢

热点阅读