簡體   English   中英

使用 jq 將 output 轉換為 JSON

[英]Convert output to JSON using jq

我需要轉換這種 output:

samaccountname: displayname
samaccountname2: displayname2

像這樣:

{
"samaccountname": "displayname",
"samaccountname2": "displayname2"
}

你能幫我一下嗎?

謝謝!

順便說一句,這是 88573394188 搜索查詢的 output,因此它需要從 pipe / stdin 接收數據。

謝謝!

如果您可以基於第一個冒號進行解析,則可以這樣做:

jq -Rn '[inputs | capture("(?<key>[^:]*): *(?<value>.*)")] | from_entries'

您可能想要添加過濾器以進行進一步的修剪。 (jq具有ltrimstrrtrimstr以防萬一。)

正則表達式 - 免費

或(除修剪外):

jq -Rn '[inputs | index(":") as $i | {key: .[:$i], value: .[1+$i:]}] | from_entries'

ldapsearch的

ldapsearch有一個選項:

-B

不要禁止顯示非ASCII值。

考慮到您將 ldapsearch 與 nowrap 一起使用,您可以使用:

ldapsearch -LLL -E pr=1000/noprompt -o ldif-wrap=no <put your stuff here> |
jq --slurp --raw-input 'split("\n\n")|map(split("\n")|map(select(.[0:1]!="#" and length>0)) |select(length > 0)|map(capture("^(?<key>[^:]*:?): *(?<value>.*)") |if .key[-1:.key|length] == ":" then .key=.key[0:-1]|.value=(.value|@base64d) else . end)| group_by(.key) | map({key:.[0].key,value:[.[].value]})| from_entries)'

解釋:

# Split entries by empty new lines
split("\n\n")|
# for each entry
map(
  # split attribute on each entry
  split("\n")|
  # drop comments and empty lines
  map(select(.[0:1]!="#" and length>0)) |
  # and empty arrays
  select(length > 0) |
  # for each attribute
  map(
    # Capture key and value, keeping a trailing ":" for base64 
    capture("^(?<key>[^:]*:?): *(?<value>.*)") |
    # for those base64, decode the value and chomp the extra ":"
    if .key[-1:.key|length] == ":" then .key=.key[0:-1]|.value=(.value|@base64d) else . end
  )|
 # Now group repeated attributes by attribute name
 group_by(.key) |
 # And join values
 map({key:.[0].key,value:[.[].value]})|
 # Finally, convert key/values to json
 from_entries
)

這也可以在沒有 "from_entries" function 的情況下完成:

jq -Rn '[ inputs |split(": ") |{ (.[0]):.[1] } ] |add'

暫無
暫無

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

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