Arrays JSON中对象数组的YAML等价物
我有一个JSON对象数组,我正试图将其转换为YAMLArrays JSON中对象数组的YAML等价物,arrays,json,types,yaml,Arrays,Json,Types,Yaml,我有一个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 - : sh
{"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;博士
你想要这个:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
映射
JSON对象的YAML等价物是一个映射,如下所示:
# flow style
{ foo: 1, bar: 2 }
请注意,块映射中键的第一个字符必须在同一列中。证明:
# OK
foo: 1
bar: 2
序列
YAML中JSON数组的等价物是一个序列,它看起来像以下两个(它们是等价的):
在块序列中,-
必须在同一列中
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
我们在一个数组(序列)中有两个:
注意-
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
}
]
}
您可以查看它(并以交互方式编辑它)。以上回答很好。另一种方法是使用伟大的yaml jq包装工具yq at 将JSON示例保存到一个文件中,比如ex.JSON,然后
yq -y '.' ex.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
…这是直接从YAML规范的示例2.4改编而来的。我更新了我的问题,以反映列表中有多个项目包含共享和日期对。@wegry:没有区别。另请参见YAML网站上的示例:。
- 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
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
yq -y '.' ex.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