提取对象的 属性 值并将其用作字典键
Extract an object's property value and use that as the dictionary key
我输入了这种格式:
[
{
"name":"Product one",
"productId":"12345",
"itemCode":"7037"
},
{
"name":"Product two",
"productId":"67890",
"itemCode":"9101"
},
{
"name":"Product three",
"productId":"111213",
"itemCode":"7047"
}
]
对于数组中的每个对象,我想获取名称 属性 的值,并将其用作结果对象的 属性 名称。我想要的输出是:
{
"Product one": {
"productId":"12345",
"itemCode":"7037"
},
"Product two": {
"productId":"67890",
"itemCode":"9101"
},
"Product three": {
"productId":"111213",
"itemCode":"7047"
}
}
这是我最接近它的地方:
.[] | { (.name) : { productId: .productId, vendorId: .vendorId } }
这是生成的输出:
{
"Product one": {
"productId": "12345",
"vendorId": null
}
}
{
"Product two": {
"productId": "67890",
"vendorId": null
}
}
{
"Product three": {
"productId": "111213",
"vendorId": null
}
}
这会创建双层嵌套产品,并且它们之间不包含空格。
提前感谢您的帮助。
将数组转换为对象的最简单方法可以说是通过 from_entries
函数,如下所示:
map({key: .name, value: del(.name)}) | from_entries
这里最简单的方法是在数组中创建三个对象,然后 "add" 它们:
map( { (.name): del(.name) } ) | add
输出:
{
"Product one": {
"productId": "12345",
"itemCode": "7037"
},
"Product two": {
"productId": "67890",
"itemCode": "9101"
},
"Product three": {
"productId": "111213",
"itemCode": "7047"
}
}
这是一个使用 reduce 的解决方案:
reduce .[] as $e (
{}
; .[$e.name] = ($e | del(.name))
)
我输入了这种格式:
[
{
"name":"Product one",
"productId":"12345",
"itemCode":"7037"
},
{
"name":"Product two",
"productId":"67890",
"itemCode":"9101"
},
{
"name":"Product three",
"productId":"111213",
"itemCode":"7047"
}
]
对于数组中的每个对象,我想获取名称 属性 的值,并将其用作结果对象的 属性 名称。我想要的输出是:
{
"Product one": {
"productId":"12345",
"itemCode":"7037"
},
"Product two": {
"productId":"67890",
"itemCode":"9101"
},
"Product three": {
"productId":"111213",
"itemCode":"7047"
}
}
这是我最接近它的地方:
.[] | { (.name) : { productId: .productId, vendorId: .vendorId } }
这是生成的输出:
{
"Product one": {
"productId": "12345",
"vendorId": null
}
}
{
"Product two": {
"productId": "67890",
"vendorId": null
}
}
{
"Product three": {
"productId": "111213",
"vendorId": null
}
}
这会创建双层嵌套产品,并且它们之间不包含空格。
提前感谢您的帮助。
将数组转换为对象的最简单方法可以说是通过 from_entries
函数,如下所示:
map({key: .name, value: del(.name)}) | from_entries
这里最简单的方法是在数组中创建三个对象,然后 "add" 它们:
map( { (.name): del(.name) } ) | add
输出:
{
"Product one": {
"productId": "12345",
"itemCode": "7037"
},
"Product two": {
"productId": "67890",
"itemCode": "9101"
},
"Product three": {
"productId": "111213",
"itemCode": "7047"
}
}
这是一个使用 reduce 的解决方案:
reduce .[] as $e (
{}
; .[$e.name] = ($e | del(.name))
)