簡體   English   中英

使用 bash/jq 將 json 單項 arrays 轉換為對象

[英]Convert json single-item arrays to objects using bash/jq

給定下面的示例 JSON:

{
  "account_number": [
    "123456"
  ],
  "account_name": [
    "name"
  ],
  "account_id": [
    654321
  ],
  "username": [
    "demo"
  ]
}

我想得到:

{
  "account_number": "123456",
  "account_name": "name",
  "account_id": 654321,
  "username": "demo"
}

目前,我用| sed 's/\[//g' | sed 's/\]//g' | jq '.'蠻力強迫它| sed 's/\[//g' | sed 's/\]//g' | jq '.' ...但當然,如果任何值包含[] ,這很丑陋並會導致問題。

我在jqflatten和其他循環和映射技術(如| jq -s '{Item:.[]} |.Item |add' | jq -s '{Item:.[]} |.Item |add'嘗試將單個項目 arrays 展平。 理想情況下,它將在將 arrays [...]扁平化為扁平元素/對象{...}的地方工作。 無論哪種方式都比替換所有出現的方括號更好。

簡短而甜蜜:

 map_values(first)

使用with_entries ,將每個值更改為自身的第一個元素:

jq 'with_entries(.value |= .[0])' file.json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM