I have a JSON array of objects that I'm trying to convert to YAML.

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

YAML中是否有一种不仅仅是JSON的等价表示?我想做点像

AAPL:
  - :
    shares: -75.088
    date: 11/27/2015
  - :
    shares: 75.088
    date: 11/26/2015

但我想出的最干净的东西是

AAPL:
  - {
    shares: -75.088,
    date: 11/27/2015
  }
  {
    shares: 75.088,
    date: 11/26/2015
  }

推荐答案

TL;DR

你想要这个:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

YAML中JSON数组的类似功能是一个序列,它看起来像以下两种(它们是等价的):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

在块序列中,-必须在同一列中.

JSON to YAML

让我们将JSON转换为YAML.以下是您的JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

等效的YAML映射为:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

请注意-和映射键的第一个字符是如何排列的.

Finally, this sequence is itself a value in a mapping with the key AAPL:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

解析它并将其转换回JSON会产生预期的结果:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

Json相关问答推荐

使用动态和可变JSON的图表多条

写入JSON文件的流

将PostgreSQL转换为JSON对象

Jolt-在数组列表中插入新的字段

PostgreSQL:删除 JSONB 数组中每个元素的特定键

使用 jq 工具将文本从 txt 文件转换为 json

我无法将来自 API 的数据显示到 FlatList 中,但我在 console.log 中看到了它.问题是什么?

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

从 json 数组中仅提取一个值导致 vb6

使用 jq Select 键:值并输出为数组

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

json和空数组

jQuery AJAX 和 JSON 格式

如何使用 SwiftyJSON 将字符串转换为 JSON

jQuery循环.each()JSON键/值不起作用

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

MVC JsonResult camelCase 序列化

类型是接口或抽象类,不能实例化

按键值过滤 JSON