我有一些我要接收的样本有效载荷,它看起来像这样:
[
{
"Id": "9",
"Line": [
{
"Amount": 100,
"Description": "Weekly Gardening Service",
"DetailType": "SalesItemLineDetail",
"Id": "1",
"LineNum": 1,
"SalesItemLineDetail": {
"ItemAccountRef": {
"name": "Landscaping Services",
"value": "45"
},
"ItemRef": {
"name": "Gardening",
"value": "6"
},
"Qty": 4,
"TaxCodeRef": {
"value": "TAX"
},
"UnitPrice": 25
}
},
{
"Amount": 100,
"DetailType": "SubTotalLineDetail",
"SubTotalLineDetail": {}
}
]
},
{
"Id": "10",
"Line": [
{
"Amount": 140,
"Description": "Weekly Gardening Service",
"DetailType": "SalesItemLineDetail",
"Id": "1",
"LineNum": 1,
"SalesItemLineDetail": {
"ItemAccountRef": {
"name": "Landscaping Services",
"value": "45"
},
"ItemRef": {
"name": "Gardening",
"value": "6"
},
"Qty": 4,
"TaxCodeRef": {
"value": "NON"
},
"UnitPrice": 35
}
},
{
"Amount": 35,
"Description": "Pest Control Services",
"DetailType": "SalesItemLineDetail",
"Id": "2",
"LineNum": 2,
"SalesItemLineDetail": {
"ItemAccountRef": {
"name": "Pest Control Services",
"value": "54"
},
"ItemRef": {
"name": "Pest Control",
"value": "10"
},
"Qty": 1,
"TaxCodeRef": {
"value": "NON"
},
"UnitPrice": 35
}
},
{
"Amount": 175,
"DetailType": "SubTotalLineDetail",
"SubTotalLineDetail": {}
}
]
}
]
这些我知道是有效的,我需要交叉引用他们,通过id,在另一个有效载荷我收到。但是,我收到的数据,我不能假设有有效的ID的。
因此,我想从上面获取所有有效的Id
,并将它们随机放入我的样本数据中,看起来像这样的($.invoices[].qbId)
:
[
{
"id": "fb2430c5-5970-46b0-9947-aaa0b9f177bb",
"invoices": [
{
"description": "2022-02-03 - 179",
"dueDate": "2022-02-03T22:51:10.206Z",
"id": "6f904b18-71c6-4fec-a016-7452f6a6b1dc",
"invoiceDate": "2022-02-03T22:51:10.347Z",
"openBalance": 200,
"paidAmount": 200,
"qbId": "1",
"totalAmount": 212
}
]
},
{
"id": "fa5b77b5-bfd4-4178-ac31-386ec83f530c",
"invoices": [
{
"description": "2022-01-12 - 95",
"dueDate": "2022-01-12T14:08:26.219Z",
"id": "05a58be3-4396-4c15-b9c2-ece68cb2b3fb",
"invoiceDate": "2022-01-12T14:08:26.399Z",
"openBalance": 7.33,
"paidAmount": 7.33,
"qbId": "",
"totalAmount": 7.33
},
{
"description": "2022-01-12 - 95",
"dueDate": "2022-01-12T14:08:26.219Z",
"id": "91f5ecd0-e18d-4029-8745-143323e02007",
"invoiceDate": "2022-01-12T14:08:26.580Z",
"openBalance": 53.13,
"paidAmount": 53.13,
"qbId": "",
"totalAmount": 53.13
}
]
}
]
这个JQ将得到我的IDsjq '.QueryResponse.Invoice | map(.Id)'
,其可以容易地被JQ消耗。现在的问题是(这是我不知道的)如何从这个数组中随机选择并更新示例负载:
jq 'map(. + {
invoices : .invoices | map(. + {qbId: ??random here })
})
'
3条答案
按热度按时间nhjlsmyf1#
如果我理解正确的话,您希望用随机生成的id字符串替换每个
id
字段(拼写可能不同,有时是Id
)。该解决方案首先使用
jq
提取所有此类id字段(以各种拼写)的路径,然后在shell中迭代结果,使用uuidgen
为每个字段生成一个id,该id被馈送到另一个jq
调用中,该调用使用setpath
更改保存到生成的id的路径处的值:tv6aics12#
下面是我使用'now'作为random的源来创建随机日期字符串的代码片段。使用数组长度作为上限,在id数组(map)中生成索引应该很简单:
llew8vvj3#
这展示了如何从数组中随机选择元素,假设一个bash或足够类似bash的环境: