![](/img/trans.png)
[英]How to insert a key-value pair after a specified key in a JSON object using jq?
[英]Insert a key value pair in each object if it is not present using jq
我正在嘗試在 JSON 文件的每一行中添加一個特定的關鍵字,如果它不存在的話。
我的初始文件:
[{"type": "STRING", "name": "Article"},
{"type": "STRING", "name": "Sellable_UOM"},
{"type": "STRING", "name": "PriceFamilyCode"},
{"type": "STRING", "name": "PriceFamilyDescription"},
{"type": "STRING", "name": "SalesDistrict"},
{"type": "DATE", "name": "FiscalWeekendDate"},
{"type": "STRING", "mode": "REPEATED", "name": "export_sql"},
{"type": "STRING", "mode": "REPEATED", "name": "post_sql"}]
預期 output:
[{"type": "STRING", "mode": "NULLABLE", "name": "Article"},
{"type": "STRING", "mode": "NULLABLE", "name": "Sellable_UOM"},
{"type": "STRING", "mode": "NULLABLE", "name": "PriceFamilyCode"},
{"type": "STRING", "mode": "NULLABLE", "name": "PriceFamilyDescription"},
{"type": "STRING", "mode": "NULLABLE", "name": "SalesDistrict"},
{"type": "DATE", "mode": "NULLABLE", "name": "FiscalWeekendDate"},
{"type": "STRING", "mode": "REPEATED", "name": "export_sql"},
{"type": "STRING", "mode": "REPEATED", "name": "post_sql"}]
要求:如果該行包含模式值,則將其插入為“模式”:“NULLABLE”在類型和名稱屬性之間。
我想要達到的最終結果是從上面預期的 output 中獲取字段及其相應的日期類型和模式,如下所示。
最后結果:
Article,STRING,NULLABLE
Sellable_UOM,STRING,NULLABLE
PriceFamilyCode,STRING,NULLABLE
PriceFamilyDescription,STRING,NULLABLE
SalesDistrict,STRING,NULLABLE
FiscalWeekendDate,DATE,NULLABLE
export_sql,STRING,REPEATED
post_sql,STRING,REPEATED
我試圖實現的命令來自預期的 output json 是,
jq -r '.[] |[ .name, .type, .mode]|@csv' file1.json | sed s/'"'//g
下面的程序通過插入mode: "NULLABLE"
對在每個沒有mode
鍵的 object 的type
和name
鍵之間。
map(select(has("mode") | not) |= {type, mode: "NULLABLE", name})
但是,如果這里的目的是將輸入 JSON 轉換為 CSV,我認為不需要中間結構。 假設mode
不存在或非空值,則可使用備用運算符進行直接轉換,如下所示。
.[] | [.type, .mode // "NULLABLE", .name] | @csv
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.