![](/img/trans.png)
[英]command output give object string how to convert it to json using jq
[英]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具有ltrimstr
和rtrimstr
以防萬一。)
或(除修剪外):
jq -Rn '[inputs | index(":") as $i | {key: .[:$i], value: .[1+$i:]}] | from_entries'
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.