【问题标题】:YAML equivalent of array of objects in JSONYAML 等效于 JSON 中的对象数组
【发布时间】:2016-03-03 13:23:49
【问题描述】:

我有一个 JSON 对象数组,我正在尝试将其转换为 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
  }

【问题讨论】:

标签: arrays json types yaml


【解决方案1】:

TL;DR

你想要这个:

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

映射

JSON 对象的 YAML 等价物是一个映射,如下所示:

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

请注意,块映射中键的第一个字符必须在同一列中。演示:

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

序列

YAML 中 JSON 数组的等价物是一个序列,它看起来像以下任何一种(它们是等价的):

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

在块序列中,-s 必须在同一列中。

JSON 到 YAML

让我们将您的 JSON 转换为 YAML。这是你的 JSON:

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

作为一个小问题,YAML 是 JSON 的超集,所以上面已经是有效的 YAML 了——但让我们实际使用 YAML 的特性来使它更漂亮。

从内到外,我们的对象看起来像这样:

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

等效的 YAML 映射为:

shares: -75.088
date: 11/27/2015

我们在一个数组(序列)中有两个:

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

注意-s 是如何排列的,映射键的第一个字符是如何排列的。

最后,这个序列本身就是与键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
    }
  ]
}

您可以看到(并以交互方式编辑)here

【讨论】:

  • 我更新了我的问题,以反映列表中有多个项目包含共享和日期对。
  • @wegry:没什么区别。另请参阅 YAML 网站上的示例:yaml.org/start.html
  • "YAML 是 JSON 的超集,所以上面已经是有效的 YAML" 所以所有的 JSON 基本上都是有效的 YAML。
【解决方案2】:

上面的答案很好。另一种方法是使用很棒的 yaml jq 包装器工具,yq at https://github.com/kislyuk/yq

将您的 JSON 示例保存到文件中,例如 ex.json,然后

yq -y '.' ex.json

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

【讨论】:

    【解决方案3】:

    如果间距太小让您感到困扰,为了补充已接受的答案,您还可以这样做:

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

    ...这直接改编自 YAML 规范的示例 2.4。

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 2019-10-02
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多