简体   繁体   中英

Convert output to JSON using jq

I need to convert this kind of output:

samaccountname: displayname
samaccountname2: displayname2

to something like this:

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

Could you please give me a hand?

Thanks!

BTW, this is the output of an LDAP Search Query, so it needs to work receiving the data from pipe / stdin.

Thanks!

If you can parse based on the first colon, this will do it:

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

You might want to add a filter to do further trimming. (jq has ltrimstr and rtrimstr in case that helps.)

regex-free

Or (apart from the trimming):

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

ldapsearch

ldapsearch has an option:

-B

Do not suppress display of non-ASCII values.

Considering you are using ldapsearch with nowrap, you can use:

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)'

Explaining:

# 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
)

This can also be done without "from_entries" function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM